Update a Label with a Swing Timer

I don’t really understand your question why you are using the Random, but here are some observations:

I want to update a JLabel with the countdown, every second.

Then you need to set the Timer to fire every second. So the parameter to the Timer is 1000, not some random number.

Also, in your actionPerformed() method you stop the Timer the first time it fires. If you are doing a count down of some kind then you would only stop the Timer when the time reaches 0.

Here is a simple example of using a Timer. It just updates the time every second:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class TimerTime extends JPanel implements ActionListener
{
    private JLabel timeLabel;

    public TimerTime()
    {
        timeLabel = new JLabel( new Date().toString() );
        add( timeLabel );

        Timer timer = new Timer(1000, this);
        timer.setInitialDelay(1);
        timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        //System.out.println(e.getSource());
        timeLabel.setText( new Date().toString() );
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("TimerTime");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new TimerTime() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

If you need more help then update your question with a proper SSCCE demonstrating the problem. All questions should have a proper SSCCE, not just a few random lines of code so we can understand the context of the code.

Leave a Comment