用Java写一个日历加钟表要带图形界面
时间: 2024-05-16 11:14:11 浏览: 51
可以使用Java Swing来实现日历和钟表的图形界面。下面是一个简单的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class CalendarClock extends JFrame {
private JLabel dateLabel, timeLabel;
public CalendarClock() {
setTitle("Calendar & Clock");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建日历和钟表标签
dateLabel = new JLabel();
timeLabel = new JLabel();
// 设置字体和对齐方式
dateLabel.setFont(new Font("Arial", Font.BOLD, 20));
dateLabel.setHorizontalAlignment(SwingConstants.CENTER);
timeLabel.setFont(new Font("Arial", Font.BOLD, 40));
timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
// 添加标签到窗口
add(dateLabel, BorderLayout.NORTH);
add(timeLabel, BorderLayout.CENTER);
// 创建定时器任务,每秒更新时间
TimerTask task = new TimerTask() {
@Override
public void run() {
// 更新日期和时间标签
Date now = new Date();
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(now);
String timeStr = new SimpleDateFormat("HH:mm:ss").format(now);
dateLabel.setText(dateStr);
timeLabel.setText(timeStr);
}
};
// 启动定时器
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 1000);
}
public static void main(String[] args) {
CalendarClock clock = new CalendarClock();
clock.setVisible(true);
}
}
```
运行上述代码,将会显示一个带有日期和时间的窗口。你可以根据需要对其进行进一步的美化和定制。