【发布时间】:2009-09-13 15:33:23
【问题描述】:
我有一个类(模拟),它创建另一个类(GUI)的实例。在类 GUI 内有一个按钮(开始),上面附有一个动作监听器。
我需要这个动作监听器在模拟中启动一个计时器,但我不知道该怎么做。
类模拟中的代码:
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() 方法不能是静态的,因为这似乎会破坏计时器...
任何帮助将不胜感激。
【问题讨论】:
-
actionPerformed 如何获得模拟?
-
抱歉,我不小心错误地发布了代码部分,actionPerformed 现在显示为:Simulation.StartTimer();
标签: java swing class timer actionlistener