📄 timerdemo.java
字号:
//多线程的应用:时钟
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
public class TimerDemo extends Frame{//继承Frame
Label timer;//声明标签
public TimerDemo() {
super("时钟");
timer = new Label("",Label.CENTER);//标签内容居中对齐
timer.setFont(new Font("宋体", Font.BOLD, 175));//设置字体
add(timer);//将timer添加到窗体中
setSize(800,200);
setVisible(true);
addWindowListener(new WindowAdapter(){//用匿名内部类关闭窗体
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[]) {
TimerDemo td = new TimerDemo();//创建窗体对象
new Timer(td).start();//创建线程对象,并启动
}
}
class Timer extends Thread {//计时器类,继承了Thread
TimerDemo tb;
Timer(TimerDemo tb) {
this.tb = tb;
}
public void run() {//线程体
while (true) {
SimpleDateFormat dateformat = new SimpleDateFormat("hh:mm:ss");//设置日期格式
String s = dateformat.format(new Date());//将当前时间用指定日期格式输出
tb.timer.setText(s);//将格式化文本(时间)在标签上输出
try {
sleep(1000);//休眠1秒钟时间,即1秒钟更新1次
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -