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

时间:2009-08-28 13:30:07

标签: java class methods call actionlistener

基本上我想做的是获取一个启动按钮来启动另一个类中运行的方法并对另一个对象起作用。

我的听众代码:

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

我的其他类的代码:

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

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

我觉得这不会太难,但我错过了一块。

4 个答案:

答案 0 :(得分:4)

在匿名类中引用内容的一种方法是使用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);
  }

或者,您可以访问封闭类型的成员(变量或方法):

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);
  }
}

答案 1 :(得分:2)

我遇到了和你一样的问题,这就是我解决问题的方法。

你可以让你的对象最终(最终CastleCrash sim = new CastleCrash();),但我不想这样做,或者你可以制作类似于setter方法的东西来在你的其他类中运行该方法:

我的侦听器类代码:

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();
}

我的其他类的代码:

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

希望这有帮助,祝你好运! :)

答案 2 :(得分:1)

McDowell几乎已经就如何从事件侦听器(或一般的匿名内部类)访问变量的示例做出了回答。然而,a more general Sun resource on Event Listeners in Swing是规范的,并且在编写时需要考虑所有注意事项。

答案 3 :(得分:0)

不知何故,您需要引用可以从actionListener调用的CastleCrash对象。

您可能希望继承JFrame,或者包含JButton的任何内容,使其具有您的main方法和CastleCrash属性,然后可以从您的匿名内部类Actionlistener中引用它。

但是 - 小心,你看起来就像在GUI事件线程中调用一个长时间运行的方法(动作监听器将被调用)。这通常是一个坏主意,您将使您的GUI无法响应。

请参阅http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html,尤其是关于如何避免该问题的想法的SwingWorker类。