2

我正在尝试为使用计时器的交通灯模拟创建动画。有一个停止模拟的按钮,但是点击它似乎不影响动画。我确实检查了动画,但动画看起来像是不同的地方。请帮忙。

在主课中:

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值永远不会改变。

4

2 回答 2

4

按钮的动作侦听器应该调用该函数以某种方式停止计时器,而不是依赖绘制事件来完成它。

编辑:这是一些代码:)

public void actionPerformed(ActionEvent e) {
    // Execute when button is pressed
    ss = true;
    System.out.println("You clicked the button");
    startAnimation();
}

并且 startAnimation 方法应该有 if(!ss) 而不是 if(!false)

于 2012-08-29T19:44:49.057 回答
3

除了 JTMon 的建议之外,您的 startAnimation 方法还包含一个逻辑炸弹

public void startAnimation() {
    if ( !false) { //<-- this will ALWAYS be true
        tm.start();
    } else {
        tm.stop();
    }
    // Checking button click
    System.out.println(ss);
}

控制计时器的 if 语句将始终尝试启动计时器

于 2012-08-29T20:31:11.150 回答