javagui数字时钟
时间: 2023-10-14 22:07:20 浏览: 34
以下是一个简单的Java GUI数字时钟示例:
```java
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DigitalClock extends JFrame {
public DigitalClock() {
setTitle("Digital Clock");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setResizable(false);
// 创建一个 JLabel 来显示时间
JLabel timeLabel = new JLabel();
timeLabel.setFont(new Font("Arial", Font.PLAIN, 60));
timeLabel.setHorizontalAlignment(JLabel.CENTER);
add(timeLabel);
// 创建一个定时器,每秒钟更新一次时间
Timer timer = new Timer(1000, e -> {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String time = sdf.format(calendar.getTime());
timeLabel.setText(time);
});
timer.start();
setVisible(true);
}
public static void main(String[] args) {
new DigitalClock();
}
}
```
这个程序使用了 `javax.swing.*` 和 `java.awt.*` 包来创建一个窗口和一个 `JLabel` 来显示时间。定时器每秒钟更新一次时间,并将其设置为 `JLabel` 的文本内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)