摇摆计时器调用动作执行两次

问题描述 投票:0回答:1

我有一个扩展了JLabel的类。我想每隔一秒就把JLabel中的文本值增加1。我使用了swing timer。我猜测它是调用了两次而不是一次的动作。

public class MineTimer extends JLabel{
    private Timer timer;
    int time = 0;

    public void start() {
        time = 0;
        timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {               
                setText("" + time++);
            }
        });


        timer.start();
    }
}

预期的输出。1秒后,JLabel的文本

1

2秒后的JLabel文本

2

3秒后的JLabel文本

3

实际输出。1秒后,JLabel的文本

2

2秒后的JLabel文本

4

3秒后的JLabel文本

6
java swing timer jlabel
1个回答
2
投票

也许你在其他地方调用了timer.start()?当你这样重写代码时,代码的表现如何?

public class MineTimer extends JLabel {
public void start() {
    new Timer(1000, new ActionListener() {
        int time = 0;
        @Override
        public void actionPerformed(ActionEvent e) {               
            setText("" + time++);
        }
    }).start();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.