Swing Timer 调用动作执行了两次

Swing Timer calling action performed twice

我有一个扩展 JLabel 的 class。我想每秒将 JLabel 中的文本值增加 1。我为此使用了摇摆计时器。但它递增 2 而不是 1。我的猜测是调用操作执行了两次而不是一次。

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();
    }
}

预期输出: 在 JLabel

的 1 秒文本之后
1

JLabel 文本 2 秒后

2

JLabel 文本 3 秒后

3

实际输出: 在 JLabel

的 1 秒文本后
2

JLabel 文本 2 秒后

4

JLabel 文本 3 秒后

6

也许您在其他地方调用 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();
  }
}