温馨提示×

java怎么实现万年历图形界面

小亿
116
2023-08-10 06:00:50
栏目: 编程语言

要实现一个万年历的图形界面,可以使用Java的Swing库来完成。以下是一个简单的示例代码:

import javax.swing.*;
import java.awt.*;
import java.time.LocalDate;
public class CalendarGUI {
private JFrame frame;
private JPanel panel;
private JLabel monthLabel;
private JLabel yearLabel;
private JButton prevButton;
private JButton nextButton;
private JTable calendarTable;
private LocalDate currentDate;
public CalendarGUI() {
frame = new JFrame("万年历");
panel = new JPanel();
monthLabel = new JLabel();
yearLabel = new JLabel();
prevButton = new JButton("上个月");
nextButton = new JButton("下个月");
calendarTable = new JTable(6, 7);
currentDate = LocalDate.now();
createGUI();
updateCalendar();
}
private void createGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(new BorderLayout());
panel.setLayout(new BorderLayout());
panel.add(monthLabel, BorderLayout.WEST);
panel.add(yearLabel, BorderLayout.CENTER);
panel.add(prevButton, BorderLayout.LINE_START);
panel.add(nextButton, BorderLayout.LINE_END);
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(calendarTable), BorderLayout.CENTER);
prevButton.addActionListener(e -> {
currentDate = currentDate.minusMonths(1);
updateCalendar();
});
nextButton.addActionListener(e -> {
currentDate = currentDate.plusMonths(1);
updateCalendar();
});
frame.setVisible(true);
}
private void updateCalendar() {
monthLabel.setText(currentDate.getMonth().toString());
yearLabel.setText(String.valueOf(currentDate.getYear()));
LocalDate firstDayOfMonth = LocalDate.of(currentDate.getYear(), currentDate.getMonth(), 1);
int firstDayOfWeek = firstDayOfMonth.getDayOfWeek().getValue();
int daysInMonth = currentDate.lengthOfMonth();
for (int i = 0; i < calendarTable.getRowCount(); i++) {
for (int j = 0; j < calendarTable.getColumnCount(); j++) {
int day = i * calendarTable.getColumnCount() + j + 1 - firstDayOfWeek;
if (day <= 0 || day > daysInMonth) {
calendarTable.setValueAt("", i, j);
} else {
calendarTable.setValueAt(day, i, j);
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(CalendarGUI::new);
}
}

这个示例代码使用了一个JFrame作为窗口容器,其中包含一个JPanel作为标题栏容器,一个JTable用于显示日历表格。通过按钮的点击事件,可以切换到上个月或下个月的日历。使用LocalDate类来获取当前日期和计算上下个月的日期。

0