此文章为Java中的时钟标签,获取系统当前时间,每一秒更新一次,并且一标签的形式保存,可以直接放在面板中使用,代码如下
import java.awt.*;
import javax.swing.JLabel;
import java.util.*;
import java.text.*;
/**
* 计时时钟
*/
public class Clocklabel
extends JLabel
implements Runnable {
private Thread clockthread = null;
public Clocklabel() {
if (clockthread == null) {
clockthread = new Thread(this, "clock");
clockthread.start();
}
}
public void run() {
while (true) {
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
DateFormat dateformatter = DateFormat.getTimeInstance();
this.setText(dateformatter.format(date));
try {
Thread.sleep(1000);
}
catch (Exception e) {}
}
}
public Thread getClockthread() {
return clockthread;
}
}