7

基本上我想要做的是获得一个开始按钮来启动在另一个类中运行并作用于另一个对象的方法。

我的听众代码:

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

4 回答 4

5

在匿名类中引用事物的一种方法是使用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);
  }
}
于 2009-08-28T13:45:09.580 回答
3

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

您可以使您的对象成为最终对象(最终 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
}

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

于 2012-02-14T06:22:03.300 回答
1

McDowell 已经用很好的例子回答了如何从事件监听器(或一般的匿名内部类)访问变量。然而,Swing 中的事件侦听器上有一个更通用的 Sun 资源,它是规范的,并且很好地概述了编写它们时要考虑的所有警告。

于 2009-08-28T13:58:47.753 回答
0

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

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

但是 - 请注意,您看起来正在从 GUI 事件线程(将调用动作侦听器)中调用一个长时间运行的方法。这通常是一个坏主意,您将导致您的 GUI 变得无响应。

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

于 2009-08-28T13:41:58.943 回答