java编写日历程序界面
时间: 2023-10-17 15:22:49 浏览: 104
Softlab3_NHF
下面是一个简单的 Java 日历程序界面的示例代码,你可以根据自己的需要进行修改和扩展:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalendarGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel currentMonthLabel;
private JButton prevMonthButton, nextMonthButton;
private JPanel calendarPanel;
private int currentYear, currentMonth;
public CalendarGUI() {
currentYear = java.time.Year.now().getValue();
currentMonth = java.time.Month.getValue();
setTitle("Calendar");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
// 创建月份标签和按钮
currentMonthLabel = new JLabel("", JLabel.CENTER);
prevMonthButton = new JButton("<<");
nextMonthButton = new JButton(">>");
prevMonthButton.addActionListener(this);
nextMonthButton.addActionListener(this);
// 创建日历面板
calendarPanel = new JPanel();
calendarPanel.setLayout(new GridLayout(7, 7));
calendarPanel.setPreferredSize(new Dimension(220, 120));
// 添加标签和按钮到顶部面板
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
topPanel.add(currentMonthLabel, BorderLayout.CENTER);
topPanel.add(prevMonthButton, BorderLayout.WEST);
topPanel.add(nextMonthButton, BorderLayout.EAST);
// 添加顶部面板和日历面板到主框架
add(topPanel, BorderLayout.NORTH);
add(calendarPanel, BorderLayout.CENTER);
// 显示日历
updateCalendar(currentYear, currentMonth);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == prevMonthButton) {
currentMonth--;
if (currentMonth == 0) {
currentMonth = 12;
currentYear--;
}
} else if (e.getSource() == nextMonthButton) {
currentMonth++;
if (currentMonth == 13) {
currentMonth = 1;
currentYear++;
}
}
updateCalendar(currentYear, currentMonth);
}
private void updateCalendar(int year, int month) {
// 清空日历面板
calendarPanel.removeAll();
// 获取当前月份的天数和第一天是星期几
java.time.YearMonth ym = java.time.YearMonth.of(year, month);
int daysInMonth = ym.lengthOfMonth();
int firstDayOfWeek = ym.atDay(1).getDayOfWeek().getValue();
// 添加星期标签
String[] weekDays = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
for (int i = 0; i < weekDays.length; i++) {
JLabel dayLabel = new JLabel(weekDays[i], JLabel.CENTER);
calendarPanel.add(dayLabel);
}
// 添加空白格子
for (int i = 1; i < firstDayOfWeek; i++) {
JLabel dayLabel = new JLabel("", JLabel.CENTER);
calendarPanel.add(dayLabel);
}
// 添加日期标签
for (int day = 1; day <= daysInMonth; day++) {
JLabel dayLabel = new JLabel(String.valueOf(day), JLabel.CENTER);
calendarPanel.add(dayLabel);
}
// 刷新标签和按钮
currentMonthLabel.setText(ym.getMonth().toString() + " " + year);
currentMonthLabel.repaint();
prevMonthButton.setEnabled(true);
nextMonthButton.setEnabled(true);
}
public static void main(String[] args) {
new CalendarGUI().setVisible(true);
}
}
```
这个程序使用 Java Swing 组件实现了一个简单的日历界面。它包括一个顶部面板,其中包含了当前月份的标签和前后月份的按钮,以及一个日历面板,用于显示日期。当用户点击前后月份的按钮时,程序会更新日历面板以显示新的日期。
阅读全文