开发者

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

开发者 https://www.devze.com 2023-03-13 03:02 出处:网络
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 ma开发者_Go百科nual

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 ma开发者_Go百科nually 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消