简体   繁体   English

Java:使用actionlistener在该类的对象上调用另一个类中的函数

[英]Java: Using an actionlistener to call a function in another class on an object from that class

Basically what I want to do is get a start button to initiate a method running in another class and acting on another object. 基本上我想要做的是获得一个启动按钮来启动在另一个类中运行的方法并作用于另一个对象。

My code for the listener: 我的听众代码:

button1a.addActionListener(new ActionListener() {
    public void actionPerformed (ActionEvent event) {
        // Figure out how to make this work
        //sim.runCastleCrash(); 
    }
} );

My code for the other class: 我的其他类的代码:

public static void main(String[] args) {
    CastleCrash sim;
    sim = new CastleCrash();
}

and

public void runCastleCrash() {
    System.out.println("Castle Crash is beginning...");
    //Other method parts here to be added
}

I get the feeling this can't be too hard, but I'm missing a piece. 我觉得这不会太难,但我错过了一块。

One way to reference things in an anonymous class is using the final keyword: 在匿名类中引用事物的一种方法是使用final关键字:

  public static void main(String[] args) {
    final Object thingIWantToUse = "Hello";

    JButton button = new JButton("Click");
    button.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        System.out.println(thingIWantToUse);
      }
    });

    JFrame frame = new JFrame();
    frame.setLayout(new FlowLayout());
    frame.add(button);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }

Alternatively, you can access members (variables or methods) of an enclosing type: 或者,您可以访问封闭类型的成员(变量或方法):

public class ActionListenerDemo2 {
  private final JFrame frame = new JFrame();
  private Object thingIWantToUse = "Hello";

  public ActionListenerDemo2() {
    JButton button = new JButton("Click");
    button.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        thingIWantToUse = "Goodbye";
        System.out.println(thingIWantToUse);
      }
    });
    frame.setLayout(new FlowLayout());
    frame.add(button);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    new ActionListenerDemo2().frame.setVisible(true);
  }
}

I've had the same problem like you and this is how i solved it. 我和你一样有同样的问题,这就是我解决它的方法。

You can either make your object final (final CastleCrash sim = new CastleCrash();), but i didn't want to do that, or you can make something like a setter method to run the method in your other class: 你可以让你的对象最终(最终CastleCrash sim = new CastleCrash();),但我不想这样做,或者你可以制作类似于setter方法的东西来在你的其他类中运行该方法:

My code for the listener class: 我的监听器类代码:

button1a.addActionListener(new ActionListener()
{

    public void actionPerformed (ActionEvent event)
    {
    //How to make this work ?
    //Like this:
    runCC();
    }
});

public void runCC()
{
    CastleCrash sim = new CastleCrash();
    sim.runCastleCrash();
}

My code for the other class: 我的其他类的代码:

public void runCastleCrash()
{   
    System.out.println("Castle Crash is beginning...");
    //Other method parts here to be added
}

Hope this is helpful, good luck ! 希望这有帮助,祝你好运! :) :)

McDowell already answers practically with good examples on how to access variables from event listeners (or anonymous inner classes in general). McDowell几乎已经就如何从事件监听器(或一般的匿名内部类)访问变量的实例做出了回答。 There is however a more general Sun resource on Event Listeners in Swing that is canonical and a good overview of all the caveats to take into account when writing them. 然而, 在Swing中的事件监听器上一个更普遍的Sun资源是规范的,并且在编写它们时需要考虑所有注意事项。

Somehow you need a reference to your CastleCrash object available to call from your actionListener. 不知何故,您需要引用可从您的actionListener调用的CastleCrash对象。

You probably want to subclass JFrame, or whatever is containing your JButton such that it has your both your main method and a CastleCrash property that can then be referenced from your anonymous inner class Actionlistener. 您可能希望子类化JFrame,或者包含JButton的任何内容,使其具有您的main方法和CastleCrash属性,然后可以从您的匿名内部类Actionlistener中引用它。

BUT - be careful, you look like you are calling what will be a long running method from within the GUI event thread (where the action listener will called). 但是 - 小心,你看起来就像在GUI事件线程中调用一个长时间运行的方法(动作监听器将被调用)。 This is generally a bad idea, you will case your GUI to become unresponsive. 这通常是一个坏主意,您将使您的GUI无法响应。

See http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html especially the bit on SwingWorker class for ideas on how to avoid that problem. 请参阅http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html,特别是有关如何避免该问题的想法的SwingWorker类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM