Search code examples
javaswingdatetimejlabel

How to display changing text in Java Swing (ie, display time with changing seconds)


I'm looking for a way to display the current date and time on a JFrame as a JLabel but have it update automagically. Once it is drawn to the pane, I shouldn't need to worry about manually updating it because it will refresh say, every 2 seconds.

Is there a proper way of doing this? Instead of manually changing the JLabel's text value every 2 seconds.


Solution

  • Use the javax.swing.Timer to ensure that updates to the Swing component occur on the EDT.

    Timer t = new javax.swing.Timer(2000, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            yourLabel.setText(...);
        }
    });
    t.start();