用Java设计日历软件 根据如下图,综合运用GUI编程、事件处理、Calendar类应用等知识设计一款月历,要求能通过输入(或选择)年月的方式正确显示当前月份的所有日期
时间: 2023-12-14 20:37:16 浏览: 110
以下是一个简单的Java月历软件的示例代码,可以根据输入的年份和月份来显示当月的所有日期:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class CalendarApp extends JFrame implements ActionListener {
private JLabel monthLabel;
private JButton prevButton, nextButton;
private JPanel monthPanel, daysPanel;
private int currentYear, currentMonth;
public CalendarApp() {
setTitle("Java月历");
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// 获取当前日期
Calendar calendar = Calendar.getInstance();
currentYear = calendar.get(Calendar.YEAR);
currentMonth = calendar.get(Calendar.MONTH);
// 构建界面
monthLabel = new JLabel(getMonthName(currentMonth) + " " + currentYear);
prevButton = new JButton("上个月");
nextButton = new JButton("下个月");
prevButton.addActionListener(this);
nextButton.addActionListener(this);
monthPanel = new JPanel(new FlowLayout());
monthPanel.add(prevButton);
monthPanel.add(monthLabel);
monthPanel.add(nextButton);
daysPanel = new JPanel(new GridLayout(0, 7));
add(monthPanel, BorderLayout.NORTH);
add(daysPanel, BorderLayout.CENTER);
// 显示当前月份的所有日期
showMonth(currentYear, currentMonth);
}
// 处理按钮事件
public void actionPerformed(ActionEvent e) {
if (e.getSource() == prevButton) {
currentMonth--;
if (currentMonth < 0) {
currentMonth = 11;
currentYear--;
}
} else if (e.getSource() == nextButton) {
currentMonth++;
if (currentMonth > 11) {
currentMonth = 0;
currentYear++;
}
}
monthLabel.setText(getMonthName(currentMonth) + " " + currentYear);
showMonth(currentYear, currentMonth);
}
// 获取月份名称
private String getMonthName(int month) {
String[] months = {"一月", "二月", "三月", "四月", "五月", "六月",
"七月", "八月", "九月", "十月", "十一月", "十二月"};
return months[month];
}
// 显示指定年月的所有日期
private void showMonth(int year, int month) {
daysPanel.removeAll();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, 1);
int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int lastDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = 1; i < firstDayOfWeek; i++) {
daysPanel.add(new JLabel());
}
for (int i = 1; i <= lastDayOfMonth; i++) {
JLabel label = new JLabel(String.valueOf(i));
label.setHorizontalAlignment(SwingConstants.CENTER);
daysPanel.add(label);
}
revalidate();
repaint();
}
public static void main(String[] args) {
new CalendarApp().setVisible(true);
}
}
```
在这个示例代码中,我们使用了Java Swing库来构建界面,使用了Calendar类来获取当前日期和处理日期相关的逻辑。在构建界面时,我们使用了JLabel、JButton和JPanel等组件,并使用了FlowLayout和GridLayout来控制布局。在处理按钮事件时,我们通过改变currentYear和currentMonth的值来更新月历的显示,然后调用showMonth方法来重新显示当前月份的所有日期。在showMonth方法中,我们使用了Calendar类来计算当前月份的第一天是星期几,以及当前月份有多少天,然后使用JLabel组件来显示所有日期。最后,我们调用revalidate和repaint方法来刷新界面。
阅读全文