📄 mainframe.java
字号:
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class MainFrame extends JFrame {
JPanel pMain;
static JLabel lbDate,lbTime;
JButton btnControl;
CurrentTimeThread ct; //声明一个显示当前日期和时间的线程对象
public MainFrame() {
super("继承Thread类创建线程");
pMain = new JPanel(new GridLayout(2, 1));
setContentPane(pMain);
lbDate = new JLabel("");
lbDate.setFont(new Font("宋体", Font.BOLD, 22));
lbDate.setForeground(Color.RED);
pMain.add(lbDate);
lbTime = new JLabel("");
lbTime.setFont(new Font("宋体", Font.BOLD, 20));
lbTime.setForeground(Color.BLUE);
pMain.add(lbTime);
//构造线程对象并让它处于运行状态
ct = new CurrentTimeThread();
ct.start(); //启动线程
setSize(280, 130);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String args[]) {
MainFrame mFrame = new MainFrame();
}
}
//显示当前日期和时间的线程类
class CurrentTimeThread extends Thread { //继承Thread类
Date dateDisplay;
GregorianCalendar gcCalendar;
String strDate, strTime;
public CurrentTimeThread() {}
//继承Thread类必须实现的run方法
public void run() {
while (true) {
displayDateTime(); //调用显示函数
try {
this.sleep(1000);
}
catch (InterruptedException e) {
JOptionPane.showMessageDialog(null, "线程中断!");
}
}
}
//显示当前日期和时间的函数
public void displayDateTime() {
dateDisplay = new Date(); //获得当前时间
gcCalendar = new GregorianCalendar();
gcCalendar.setTime(dateDisplay);
//从当前时间中提取日期和时间,并格式化
strDate = String.format("今天是 %1$d年%2$02d月%3$02d日",
gcCalendar.get(Calendar.YEAR),
gcCalendar.get(Calendar.MONTH) + 1,
gcCalendar.get(Calendar.DAY_OF_MONTH));
strTime = String.format("当前时间:%1$02d:%2$02d:%3$02d",
gcCalendar.get(Calendar.HOUR_OF_DAY),
gcCalendar.get(Calendar.MINUTE),
gcCalendar.get(Calendar.SECOND));
//显示当前日期和时间
MainFrame.lbDate.setText(strDate);
MainFrame.lbTime.setText(strTime);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -