每次单击按钮时计时器都会增加速度

Timer increasing speed every time I click a button

我想在每次单击按钮时在小程序中执行一个动画。我第一次点击按钮一切正常。但是第二次,动画的速度增加了。第三次动画速度增加了一点点,第四次,第五次,...

我不知道计时器发生了什么。我该如何解决?

在小程序中我使用了这段代码:

JButton btnIniciar = new JButton("Iniciar");
    btnIniciar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {     
            Timer timer = new Timer(50, new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    //I have a list of packages to animate
                    for (Package p: listaPaquetes){
                        p.animate();
                        panel.repaint();
                    }                             
                }
            });

            timer.start();
        }

这是面板中重绘的代码:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);     
    //I use the same list of the applet   
    for (Package p: listaPaquetes){
        //Paint the package
        p.paintPackage(g);
    }

}

This is how it works, the animation sends packages from left to right

当您按下按钮时,您正在创建新的 javax.swing.Timer 并调用 timer.start(),在本例中,它被安排在按钮按下后 运行 50 毫秒,并每 50 毫秒重复一次。

当你第二次按下按钮时,你创建并启动了另一个定时器(一个新的),它再次每 50 毫秒工作一次,初始延迟为 50 毫秒。您现在实质上是将重绘调用的数量加倍。

第三次按下时,您将重绘调用次数增加三倍,因为您有 3 个计时器 运行ning。

如果您的按钮按下时间正确,速度看起来会增加三倍(按 3 次按钮)。

如果你不想要这种行为,你可以阻止 timer 到 运行 如果它已经 运行ning 像这样:

private Timer timer = null;

// ...

JButton btnIniciar = new JButton("Iniciar");
btnIniciar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) { 
        // prevent the timer from running again if it is already running
        if ( timer != null && timer.isRunning() ) return;

        timer = new Timer(50, new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                //I have a list of packages to animate
                for (Package p: listaPaquetes){
                    p.animate();
                    panel.repaint();
                }                             
            }
        });

        timer.start();
    }

请注意,您需要将timer设为实例变量。您也可以替换行:

if ( timer != null && timer.isRunning() ) return;

if ( timer != null ) return;

我只是想告诉你 TimerisRunning() 方法。

您也可以通过调用 timer.stop() 方法停止 timer