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

Myl*_*les 6 java methods class call actionlistener

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

我的听众代码:

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

我的其他类的代码:

public static void main(String[] args) {
    CastleCrash sim;
    sim = new CastleCrash();
}
Run Code Online (Sandbox Code Playgroud)

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

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

McD*_*ell 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);
  }
Run Code Online (Sandbox Code Playgroud)

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)