Java:使用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 } 

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

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

我和你一样有同样的问题,这就是我解决它的方法。

你可以让你的对象最终(最终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 } 

希望这是有帮助的,祝你好运! 🙂

McDowell几乎已经就如何从事件监听器(或一般的匿名内部类)访问变量提供了很好的例子。 然而, 在Swing中的事件监听器上有一个更普遍的Sun资源是规范的,并且在编写它们时需要考虑所有警告的良好概述。

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

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

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

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