据如下图,综合运用GUI编程、事件处理、Calendar类应用等知识设计 一款月历,要求能通过输入(或选择)年月的方式正确显示当前月份的所有日期。
时间: 2024-02-11 09:06:15 浏览: 158
以下是一个简单的Java月历程序,使用了Swing GUI库、ActionListener接口和Calendar类来实现。该程序可以根据用户输入的年份和月份生成并显示月历。
```java
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CalendarApp implements ActionListener {
private JFrame frame;
private JPanel monthPanel, yearPanel, datePanel;
private JLabel monthLabel, yearLabel;
private JComboBox<String> monthBox, yearBox;
private JButton updateButton;
public CalendarApp() {
// 创建主窗口
frame = new JFrame("月历");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
// 创建月份选择面板
monthPanel = new JPanel();
monthLabel = new JLabel("月份:");
monthBox = new JComboBox<String>();
for(int i = 1; i <= 12; i++) {
monthBox.addItem(String.valueOf(i));
}
monthPanel.add(monthLabel);
monthPanel.add(monthBox);
// 创建年份选择面板
yearPanel = new JPanel();
yearLabel = new JLabel("年份:");
yearBox = new JComboBox<String>();
for(int i = 1900; i <= 2100; i++) {
yearBox.addItem(String.valueOf(i));
}
yearPanel.add(yearLabel);
yearPanel.add(yearBox);
// 创建日期显示面板
datePanel = new JPanel(new GridLayout(7, 7));
updateCalendar(Calendar.getInstance());
// 创建更新按钮
updateButton = new JButton("更新");
updateButton.addActionListener(this);
// 将所有面板添加到主窗口中
frame.add(monthPanel, BorderLayout.NORTH);
frame.add(yearPanel, BorderLayout.CENTER);
frame.add(datePanel, BorderLayout.SOUTH);
frame.add(updateButton, BorderLayout.EAST);
// 显示主窗口
frame.setVisible(true);
}
// 更新月历
private void updateCalendar(Calendar cal) {
datePanel.removeAll();
// 设置日期为当月1号
cal.set(Calendar.DAY_OF_MONTH, 1);
// 获取当月第一天是星期几
int firstDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
// 添加星期标签
String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
for(int i = 0; i < weekDays.length; i++) {
datePanel.add(new JLabel(weekDays[i], JLabel.CENTER));
}
// 添加日期
for(int i = 1; i < firstDayOfWeek; i++) {
datePanel.add(new JLabel(""));
}
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
for(int i = 1; i <= daysInMonth; i++) {
datePanel.add(new JLabel(String.valueOf(i), JLabel.CENTER));
}
frame.validate();
}
// 处理更新按钮事件
public void actionPerformed(ActionEvent e) {
if(e.getSource() == updateButton) {
int year = Integer.valueOf((String) yearBox.getSelectedItem());
int month = Integer.valueOf((String) monthBox.getSelectedItem()) - 1;
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1);
updateCalendar(cal);
}
}
public static void main(String[] args) {
new CalendarApp();
}
}
```
该程序包含三个面板:月份选择面板、年份选择面板和日期显示面板。月份和年份可以通过下拉框进行选择,日期显示面板根据用户选择的年份和月份显示当前月份的所有日期。用户可以点击“更新”按钮来更新月历。
阅读全文