目录
实现创建一个数字时钟的窗口,并不断显示当前时间。
对于 GUI 编程初学者来说,是一个不错的示例。
下面是这段代码的详细解析和说明:
1. 创建窗口和标签
程序使用 JFrame 和 JLabel 两个类创建了一个窗口和一个标签,用于在窗口中显示数字时钟。
// 创建窗口和标签
frame = new JFrame("数字时钟");
label = new JLabel();
label.setFont(new Font("楷体", Font.BOLD, 160)); // 设置标签的字体样式
frame.add(label);
frame.setSize(700, 500); // 设置窗口大小
frame.setLocation(600,250); // 设置窗口位置
frame.setVisible(true); // 显示窗口
2. 创建线程并启动
程序使用 Runnable 接口创建了一个线程,并在构造函数中对该线程进行启动。
// 创建线程
Thread thread = new Thread(this);
// 启动线程
thread.start();
3. 实现线程的运行 run() 方法
在 run() 方法中,程序不断循环获取当前时间并设置标签的文本,以便每秒更新一次数字时钟的显示。程序在设置标签文本后使用 Thread.sleep(1000) 让线程暂停一秒,以确保数字时钟每秒更新一次。
@Override
public void run() {
while (true) {
// 获取当前时间
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String time = format.format(date);
// 设置标签的文本
label.setText(time);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
4. 程序入口点
使用 main 方法作为程序的入口点,调用 DigitalClock() 构造函数创建新的数字时钟窗口,启动数字时钟程序。
public static void main(String[] args) {
new DigitalClock();
}
5. 页面显示
程序将数字时钟展示为一个 JFrame 应用窗口,窗口标题为“数字时钟”。标签标记的需要显示时间的行的字体设置为大号。窗口大小设为 700 * 500,位置位置设为 (600, 250),其中的数值均需根据实际情况选择合适的值。
public DigitalClock() {
// 创建窗口和标签
frame = new JFrame("数字时钟");
label = new JLabel();
label.setFont(new Font("楷体", Font.BOLD, 160));
frame.add(label);
frame.setSize(700, 500);
frame.setLocation(600, 250);
frame.setVisible(true);// 创建线程
Thread thread = new Thread(this);
// 启动线程
thread.start();
}
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DigitalClock implements Runnable {
// Swing 窗口和标签
private JFrame frame;
private JLabel label;
public DigitalClock() {
// 创建窗口和标签
frame = new JFrame("数字时钟");
label = new JLabel();
label.setFont(new Font("楷体", Font.BOLD, 160));
frame.add(label);
frame.setSize(700, 500);
frame.setLocation(600,250);
frame.setVisible(true);
// 创建线程
Thread thread = new Thread(this);
// 启动线程
thread.start();
}
@Override
public void run() {
while (true) {
// 获取当前时间
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String time = format.format(date);
// 设置标签的文本
label.setText(time);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new DigitalClock();
}
}