Java:使用动作侦听器在该类的对象上调用另一个类中的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1346978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:28:38  来源:igfitidea点击:

Java: Using an actionlistener to call a function in another class on an object from that class

javaclassmethodscallactionlistener

提问by Myles

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

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

My code for the listener:

我的听众代码:

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

My code for the other class:

我的另一个类的代码:

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

and

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.

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

采纳答案by McDowell

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

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

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

回答by Alex Stoddard

Somehow you need a reference to your CastleCrash object available to call from your actionListener.

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

You probably want to subclass JFrame, or whatever is containing your JButton such that it has your both your main method and a CastleCrash property that can then be referenced from your anonymous inner class Actionlistener.

您可能想要子类化 JFrame 或包含 JButton 的任何内容,以便它具有您的主方法和 CastleCrash 属性,然后可以从您的匿名内部类 Actionlistener 中引用该属性。

BUT - be careful, you look like you are calling what will be a long running method from within the GUI event thread (where the action listener will called). This is generally a bad idea, you will case your GUI to become unresponsive.

但是 - 小心,您看起来像是从 GUI 事件线程(将调用操作侦听器)中调用将是长时间运行的方法。这通常是一个坏主意,您会使 GUI 变得无响应。

See http://java.sun.com/products/jfc/tsc/articles/threads/threads1.htmlespecially the bit on SwingWorker class for ideas on how to avoid that problem.

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

回答by Boris Terzic

McDowell already answers practically with good examples on how to access variables from event listeners (or anonymous inner classes in general). There is however a more general Sun resource on Event Listeners in Swingthat is canonical and a good overview of all the caveats to take into account when writing them.

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

回答by DarkAngel

I've had the same problem like you and this is how i solved it.

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

You can either make your object final (final CastleCrash sim = new CastleCrash();), but i didn't want to do that, or you can make something like a setter method to run the method in your other class:

您可以使您的对象成为最终对象(final CastleCrash sim = new CastleCrash();),但我不想这样做,或者您可以创建类似 setter 方法的东西来在您的其他类中运行该方法:

My code for the listener class:

我的侦听器类代码:

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

My code for the other class:

我的另一个类的代码:

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

Hope this is helpful, good luck ! :)

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