简体   繁体   中英

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.

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

Use Swing Timer . As the tutorial explains, it is the required tool for the job.

The only alternative to their use is the embedding of a SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait() in a TimerTask .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM