使用Calendar.hour Calendar.minute Calendar.second Calendar.AM_PM方法创建javajui数字时钟
时间: 2023-07-15 12:13:25 浏览: 208
以下是使用Java Swing创建数字时钟的示例代码:
```java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.*;
public class DigitalClock extends JFrame implements ActionListener {
private JLabel timeLabel;
public DigitalClock() {
setTitle("Digital Clock");
setSize(200, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeLabel = new JLabel();
timeLabel.setFont(new Font("Arial", Font.PLAIN, 36));
timeLabel.setHorizontalAlignment(JLabel.CENTER);
updateTime();
add(timeLabel, BorderLayout.CENTER);
Timer timer = new Timer(1000, this);
timer.start();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
updateTime();
}
private void updateTime() {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String amPm = calendar.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM";
String time = String.format("%02d:%02d:%02d %s", hour, minute, second, amPm);
timeLabel.setText(time);
}
public static void main(String[] args) {
new DigitalClock();
}
}
```
这个数字时钟程序会每秒钟更新一次时间,并将时间以"HH:mm:ss a"的格式显示在屏幕中央。你可以根据需要调整程序的字体、大小和位置等属性。
阅读全文