I’m trying to create animation for a traffic light simulation that uses a timer. There is a button to stop the simulation, but clicking it does not seem to affect the animation. I did check in the animation but the animation seem like different places. Please help.
In the main class:
DataModels dm = new DataModels();
Simulation sm = new Simulation(dm);
sm.go();
Here is the simulation class:
public class Simulation extends JPanel implements ActionListener {
DataModels dm;
Timer tm = new Timer(20, this);
private boolean ss = false;
public Simulation(DataModels dm) {
this.dm = dm;
// redLightTime= dm.getRedLight()*1000;
}
public void go() {
sm = new Simulation(dm);
simulation = new JFrame();
simulation.setTitle("Traffic light and Car park Siumulation");
simulation.setSize(800, 700);
simulation.setResizable(false);
simulation.setVisible(true);
simulation.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
simulation.add(sm, BorderLayout.CENTER);
// Command button panel
JPanel command = new JPanel();
command.setPreferredSize(new Dimension(800, 100));
// Pause or play button
JButton pauseplayB = new JButton("Pause");
pauseplayB.setSize(new Dimension(50, 50));
pauseplayB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
ss = true;
System.out.println("You clicked the button");
}
});
command.add(pauseplayB);
JButton stopB = new JButton("Stop");
JButton saveB = new JButton("Save");
command.setLayout(new GridLayout(1, 1));
command.add(stopB);
command.add(saveB);
simulation.add(command, BorderLayout.SOUTH);
}
Now paintComponent will change based on timer change. The following code is also in the Simulation class.
public void paintComponent(Graphics g) {
// Many other actions
// ....
startAnimation();
}
public void startAnimation() {
if ( !false) {
tm.start();
} else {
tm.stop();
}
// Checking button click
System.out.println(ss);
}
According to the console output, the ss value never changes.
The button’s action listener should call the function to stop the timer somehow and not rely on the paint event to do it.
EDIT: Here is some code 🙂
And the startAnimation method should have if(!ss) instead of if(!false)