我正在尝试为使用计时器的交通灯模拟创建动画。有一个停止模拟的按钮,但是点击它似乎不影响动画。我确实检查了动画,但动画看起来像是不同的地方。请帮忙。
在主课中:
DataModels dm = new DataModels();
Simulation sm = new Simulation(dm);
sm.go();
这是模拟类:
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);
}
现在paintComponent
将根据计时器的变化而变化。下面的代码也在Simulation
类中。
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);
}
根据控制台输出,该ss
值永远不会改变。