【问题标题】:Using an ActionListener in one class to start a timer in another class在一个类中使用 ActionListener 在另一个类中启动计时器
【发布时间】: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


【解决方案1】:

this 作为参数传递给GUI 构造函数。

一般来说最好避免这样的循环引用。 GUISimulator 都相互依赖。该解决方案的本质是将 GUI 从有趣的特定领域行为中分离出来。

(顺便说一句:我会强烈避免将静态变量用于常量以外的任何东西。还要避免非私有实例变量。但不要扩展JFrame!)

你应该添加一些可怕的样板来防止多线程。

public static void main(final String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
                Simulation sim = new Simulation();
    }});
}

【讨论】:

  • 我很抱歉,我在发布的代码中犯了一个错误。 “主要构造者”实际上是“模拟”指导员。由于 sim 本身就是一个“模拟”对象,所以我不认为它不能成为 GUI 构造函数的参数......
【解决方案2】:

我要做的是让您的 GUI 类通过 getButton() 方法公开按钮,然后在创建 GUI 对象后,您的 Simulation 类可以将自己的 ActionListener 添加到按钮,例如control.getButton().addActionListener(new ActionListener()...等

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多