我有一个类(模拟)创建另一个类(GUI)的实例。在类 GUI 中有一个按钮(开始),它附有一个 Action 监听器。
我需要这个 actionlistener 来在模拟中启动一个计时器,但我不知道该怎么做。
类模拟中的代码:
public class Simulation{
private static JFrame frame;
private static GUI control;
public static Integer xcontrol = 100, ycontrol = 100;
public Timer timer;
public int steps;
public static void main(String[] args) {
Simulation sim = new Simulation ();
}
public Simulation() {
frame = new JFrame("Action Listener Test");
frame.setLayout(new BorderLayout(1,0));
control = new GUI (xcontrol, ycontrol);
frame.getContentPane().add(control , BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void StartTimer() {
timer.start();
System.out.println("It worked!");
}
类 GUI 中的代码:
panel1.add(button1a);
button1a.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
Simulation.StartTimer();
}
} );
Eclipse 告诉我的错误是“Simulation.timer.start();” :
不能从类型 Simulation 对非静态方法 StartTimer() 进行静态引用。
但是 StartTimer() 方法不能是静态的,因为这似乎会破坏计时器...
如有任何帮助,我们将不胜感激。
最佳答案
将 this
作为参数传递给 GUI
构造函数。
通常最好避免这种循环引用。 GUI
和Simulator
都变得相互依赖。解决方案的本质是将 GUI 从有趣的特定领域行为中分离出来。
(顺便说一句:我会强烈避免将静态变量用于除常量以外的任何东西。还要避免使用非私有(private)实例变量。但要注意不要扩展 JFrame
!)
您应该添加一些可怕的样板文件以防止多线程。
public static void main(final String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
Simulation sim = new Simulation();
}});
}
关于java - 在一个类中使用 ActionListener 来启动另一个类中的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1418007/