在Java中要实现时间的动态显示有不少种方法。下面就介绍其中一种简单的方法给你们。java
Swing中的计时器Timer,主要用到javax.swing.*包下的Timer类,该类能够周期的触发ActionEvent事件。ide
什么都不说,直接上代码:3d
private Timer time;
//时间显示
private JLabel getTimelabel() {
if (timelabel == null) {
timelabel = new JLabel("");
timelabel.setBounds(5, 65, 200, 20);
timelabel.setFont(new Font("微软雅黑", Font.BOLD, 12));
timelabel.setForeground(new Color(182, 229, 248));
time = new Timer(1000,new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
timelabel.setText(new SimpleDateFormat("yyyy年MM月dd日 EEEE hh:mm:ss").format(new Date()));
}
});
time.start();
}
return timelabel;
}
Timer能够经过start()方法来启动,stop()方法既是中止Timer。code
时间代码:orm
timelabel.setText(new SimpleDateFormat("yyyy年MM月dd日 EEEE hh:mm:ss").format(new Date()));
时间动态显示的主要代码:blog
time = new Timer(1000,new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
timelabel.setText(new SimpleDateFormat("yyyy年MM月dd日 EEEE hh:mm:ss").format(new Date()));
}
});
time.start();
最终在界面中的显示结果为:事件