代码:
package test;
import java.awt.BorderLayout;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Demo18 {
public static void main(String[] args) {
MyFrame frame=new MyFrame();
MyThread thread=new MyThread(MyFrame.clock);
thread.start();
}
}
class MyFrame extends JFrame{
static JLabel clock;
MyFrame(){
setTitle("电子时钟");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(240,80);
clock=new JLabel();
//设置标签居中显示
clock.setHorizontalAlignment(JLabel.CENTER);
setVisible(true);
//设置边框布局,中间的位置
add(clock,BorderLayout.CENTER);
}
}
class MyThread extends Thread{
JLabel c;
public MyThread(JLabel c) {
super();
this.c = c;
}
@Override
public void run() {
while(true) {
c.setText(getTime());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public String getTime() {
Date date=new Date();
SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return s.format(date);
}
}
运行结果: