b) Make the clock show the current time. For this you should use the Calendar class from java.util with: ● Calendar.getInstance() - create Calendar object for current date/time ● get(field) - return integer field from Calendar object, where field may be Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND, Calendar.AM_PM, etc. ● the value returned from Calendar.AM_PM may be compared with the values Calendar.AM and Calendar.PM to determine if it is before or after mid-day Create a function that runs continuously and updates the display to always show the current time.怎么做
时间: 2024-02-05 11:03:31 浏览: 122
java时间 java.util.Calendar深入分析
你可以使用以下代码实现这个任务:
```java
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Clock extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel timeLabel;
public Clock() {
super("Current Time");
timeLabel = new JLabel();
timeLabel.setFont(new Font("Arial", Font.PLAIN, 48));
setLayout(new GridLayout(1, 1));
add(timeLabel);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void updateTime() {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int amPm = calendar.get(Calendar.AM_PM);
String amPmStr = (amPm == Calendar.AM) ? "AM" : "PM";
String time = String.format("%02d:%02d:%02d %s", hour, minute, second, amPmStr);
timeLabel.setText(time);
}
public static void main(String[] args) {
Clock clock = new Clock();
while (true) {
clock.updateTime();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这个代码定义了一个 `Clock` 类,它继承了 `JFrame` 类,用于显示当前时间。在 `Clock` 类中,我们创建了一个标签 `timeLabel`,用于显示当前时间。然后我们使用 `GridLayout` 将标签放置在 `JFrame` 中。在 `updateTime()` 方法中,我们使用 `Calendar` 类获取当前时间,并将其格式化为字符串。最后我们将时间字符串设置到标签中。
在 `main()` 方法中,我们创建了一个 `Clock` 对象,并在一个无限循环中不断更新时间,并在每次更新后等待 1 秒钟。这样就可以保证时间的实时更新。
阅读全文