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 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
.
精彩评论