用Java.swing 写一个日历
时间: 2024-03-14 13:46:58 浏览: 144
基于Java Swing实现的日历记事本系统【源码+报告文档】
5星 · 资源好评率100%
好的,以下是一个简单的Java Swing日历实现:
```
import javax.swing.*;
import java.awt.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class CalendarApp extends JFrame {
private JLabel monthLabel;
private JPanel monthPanel;
private JPanel dayPanel;
private JLabel[] dayLabels;
public CalendarApp() {
setTitle("Calendar");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 创建月份标签
monthLabel = new JLabel();
monthLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(monthLabel, BorderLayout.NORTH);
// 创建月份面板
monthPanel = new JPanel(new GridLayout(0, 7));
add(monthPanel, BorderLayout.CENTER);
// 创建日期面板
dayPanel = new JPanel(new GridLayout(0, 7));
add(dayPanel, BorderLayout.SOUTH);
// 创建日期标签
dayLabels = new JLabel[42];
for (int i = 0; i < dayLabels.length; i++) {
dayLabels[i] = new JLabel();
dayLabels[i].setHorizontalAlignment(SwingConstants.CENTER);
dayPanel.add(dayLabels[i]);
}
// 设置窗口大小并显示
setSize(400, 300);
setVisible(true);
// 更新日历
updateCalendar();
}
private void updateCalendar() {
// 获取当前月份和年份
Calendar calendar = new GregorianCalendar();
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
// 设置月份标签
monthLabel.setText((month + 1) + "/" + year);
// 清除日历
for (int i = 0; i < dayLabels.length; i++) {
dayLabels[i].setText("");
}
// 获取当前月份的第一天
calendar.set(Calendar.DAY_OF_MONTH, 1);
int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
// 设置月份面板
String[] daysOfWeek = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
for (int i = 0; i < daysOfWeek.length; i++) {
JLabel label = new JLabel(daysOfWeek[i]);
label.setHorizontalAlignment(SwingConstants.CENTER);
monthPanel.add(label);
}
for (int i = 1; i < firstDayOfWeek; i++) {
monthPanel.add(new JLabel());
}
for (int i = 1; i <= calendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
JLabel label = new JLabel(Integer.toString(i));
label.setHorizontalAlignment(SwingConstants.CENTER);
monthPanel.add(label);
}
}
public static void main(String[] args) {
new CalendarApp();
}
}
```
这个日历应用程序使用了Java的Swing组件和Calendar类来生成日历。它包括一个月份标签、一个月份面板和一个日期面板。在月份面板中,我们将星期几的名称添加到第一行,并在第二行添加第一个日期。在日期面板中,我们添加了每个日期的标签,并将它们按照星期几的顺序排列。
阅读全文