javaGUI通过下拉框选择日期来显示日历,不要额外加按钮
时间: 2023-07-02 14:09:05 浏览: 125
可以使用JComboBox来创建下拉框,然后根据选择的日期更新日历显示。
下面是一个简单的实现,可以根据需要进行修改和优化:
```java
import java.awt.*;
import java.awt.event.*;
import java.time.*;
import java.time.format.*;
import javax.swing.*;
public class CalendarGUI extends JFrame implements ActionListener {
private final JComboBox<String> yearBox, monthBox;
private final JLabel[] dayLabels;
private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-M-d");
public CalendarGUI() {
setTitle("Calendar");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Year:"));
yearBox = new JComboBox<>();
for (int year = LocalDate.now().getYear() - 10; year <= LocalDate.now().getYear() + 10; year++) {
yearBox.addItem(String.valueOf(year));
}
yearBox.setSelectedItem(String.valueOf(LocalDate.now().getYear()));
yearBox.addActionListener(this);
topPanel.add(yearBox);
topPanel.add(new JLabel("Month:"));
monthBox = new JComboBox<>();
for (int month = 1; month <= 12; month++) {
monthBox.addItem(String.valueOf(month));
}
monthBox.setSelectedItem(String.valueOf(LocalDate.now().getMonthValue()));
monthBox.addActionListener(this);
topPanel.add(monthBox);
add(topPanel, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new GridLayout(7, 7));
String[] weekDays = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
for (String weekDay : weekDays) {
centerPanel.add(new JLabel(weekDay, SwingConstants.CENTER));
}
dayLabels = new JLabel[42];
for (int i = 0; i < dayLabels.length; i++) {
dayLabels[i] = new JLabel("", SwingConstants.CENTER);
centerPanel.add(dayLabels[i]);
}
updateCalendar();
add(centerPanel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == yearBox || e.getSource() == monthBox) {
updateCalendar();
}
}
private void updateCalendar() {
int year = Integer.parseInt((String) yearBox.getSelectedItem());
int month = Integer.parseInt((String) monthBox.getSelectedItem());
LocalDate date = LocalDate.of(year, month, 1);
int firstDayOfWeek = date.getDayOfWeek().getValue() % 7;
int lastDay = date.plusMonths(1).minusDays(1).getDayOfMonth();
for (int i = 0; i < dayLabels.length; i++) {
if (i < firstDayOfWeek || i >= firstDayOfWeek + lastDay) {
dayLabels[i].setText("");
} else {
dayLabels[i].setText(String.valueOf(i - firstDayOfWeek + 1));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(CalendarGUI::new);
}
}
```
这个GUI界面包含一个顶部面板和一个中心面板。顶部面板包含两个下拉框,用于选择年份和月份;中心面板包含一个网格布局,用于显示日历。网格布局中第一行为星期几的标签,接下来是42个用于显示日期的标签(最多有6*7=42天)。当用户选择年份或月份时,通过计算更新中心面板中的日期标签。
阅读全文