要實(shí)現(xiàn)一個(gè)萬年歷的圖形界面,可以使用Java的Swing庫來完成。以下是一個(gè)簡單的示例代碼:
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("上個(gè)月");
nextButton = new JButton("下個(gè)月");
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);
}
}
這個(gè)示例代碼使用了一個(gè)JFrame作為窗口容器,其中包含一個(gè)JPanel作為標(biāo)題欄容器,一個(gè)JTable用于顯示日歷表格。通過按鈕的點(diǎn)擊事件,可以切換到上個(gè)月或下個(gè)月的日歷。使用LocalDate
類來獲取當(dāng)前日期和計(jì)算上下個(gè)月的日期。