[英]Java: Using an actionlistener to call a function in another class on an object from that class
基本上我想要做的是获得一个启动按钮来启动在另一个类中运行的方法并作用于另一个对象。
我的听众代码:
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对象。
您可能希望子类化JFrame,或者包含JButton的任何内容,使其具有您的main方法和CastleCrash属性,然后可以从您的匿名内部类Actionlistener中引用它。
但是 - 小心,你看起来就像在GUI事件线程中调用一个长时间运行的方法(动作监听器将被调用)。 这通常是一个坏主意,您将使您的GUI无法响应。
请参阅http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html,特别是有关如何避免该问题的想法的SwingWorker类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.