Search code examples
javaswingtimerjlabel

Swing Timer calling action performed twice


I have a class that extends JLabel. I want to increase the text value in JLabel by 1 after every second. I have used swing timer for it. But it is incrementing 2 instead of 1. My guess is it is calling action performed two times instead of one time.

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

Expected output: After 1 sec text of JLabel

1

After 2 sec text of JLabel

2

After 3 sec text of JLabel

3

Actual output: After 1 sec text of JLabel

2

After 2 sec text of JLabel

4

After 3 sec text of JLabel

6

Solution

  • Maybe you're calling timer.start() somewhere else? How does the code behave when you rewrite it like this?

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