Java:使用动作侦听器在该类的对象上调用另一个类中的函数 [英] Java: Using an actionlistener to call a function in another class on an object from that class

查看:20
本文介绍了Java:使用动作侦听器在该类的对象上调用另一个类中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically what I want to do is get a start button to initiate a method running in another class and acting on another object.

我的监听器代码:

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
}

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

I get the feeling this can't be too hard, but I'm missing a piece.

推荐答案

在匿名类中引用事物的一种方法是使用 final 关键字:

One way to reference things in an anonymous class is using the final keyword:

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

这篇关于Java:使用动作侦听器在该类的对象上调用另一个类中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆