java怎么把calendar里的时间实时放进Jlabel
时间: 2023-07-15 20:12:08 浏览: 50
可以使用Java Swing中的JLabel类和Timer类来实现将Calendar中的时间实时显示在JLabel上的功能。
首先,创建一个JLabel对象并将其添加到你的窗口中。然后,使用Timer类来定期更新JLabel中的文本,以显示最新的时间。以下是示例代码:
```java
import javax.swing.*;
import java.awt.event.*;
import java.util.Calendar;
public class Clock extends JFrame {
private JLabel timeLabel;
public Clock() {
super("Clock");
// 创建JLabel并添加到窗口中
timeLabel = new JLabel();
add(timeLabel);
// 创建计时器,每秒更新一次时间
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
// 更新JLabel中的文本
timeLabel.setText(String.format("%02d:%02d:%02d", hour, minute, second));
}
});
timer.start();
setSize(200, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Clock();
}
}
```
在上述示例代码中,我们创建了一个名为Clock的JFrame窗口,并在其中添加了一个JLabel对象。然后创建了一个计时器Timer,该计时器每秒钟更新一次JLabel中的文本,以显示当前时间。在计时器的actionPerformed()方法中,我们使用Calendar.getInstance()方法获取当前时间,并将其格式化为字符串,然后更新JLabel中的文本。
运行上述代码将显示一个带有实时时间的窗口。
相关推荐
![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)