简体   繁体   中英

Using an ActionListener in one class to start a timer in another class

I have a class (simulation) which creates an instance of another class (GUI). Inside the class GUI there is a button (start) which has an actionlistener attached to it.

I need this actionlistener to start a timer in simulation but I can't figure out how to do it.

Code in Class Simulation:

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

Code in Class GUI:

        panel1.add(button1a);

            button1a.addActionListener(new ActionListener() {
                public void actionPerformed (ActionEvent event) {
                    Simulation.StartTimer();
                    }
                } );

The error Eclipse tells me there is, is that for "Simulation.timer.start();" :

Cannot make a static reference to the non-static method StartTimer() from the type Simulation.

However the method StartTimer() cannot be static as this seems to break the timer...

Any help would be very appreciated.

Pass this as an argument to the GUI constructor.

In general it is best to avoid such cyclic references. Both the GUI and Simulator become dependent upon one another. The essence of the solution is to separate out the GUI from the interesting domain-specific behaviour.

(BTW: I would strongly avoid using static variables for anything other than constants. Also avoid non-private instance variables. But point for not extending JFrame !)

There is some hideous boilerplate that you should add to prevent multithreading.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM