javaGUI显示日历小程序,不用字符串,使用下拉框,通过选择下拉框的年,月显示对应的当月日历
时间: 2023-10-03 16:10:08 浏览: 121
java日历小程序
这是一个基本的 Java GUI 显示日历的小程序,使用了下拉框,通过选择下拉框的年、月显示对应的当月日历。程序中没有使用字符串。
```java
import javax.swing.*;
import java.awt.event.*;
import java.util.Calendar;
public class CalendarGUI {
private JFrame frame;
private JComboBox<Integer> yearComboBox;
private JComboBox<Integer> monthComboBox;
private JLabel[] dayLabels;
public CalendarGUI() {
frame = new JFrame("Calendar");
frame.setSize(400, 400);
frame.setLayout(null);
yearComboBox = new JComboBox<>();
for (int i = 1900; i <= 2100; i++) {
yearComboBox.addItem(i);
}
yearComboBox.setBounds(20, 20, 80, 30);
frame.add(yearComboBox);
monthComboBox = new JComboBox<>();
for (int i = 1; i <= 12; i++) {
monthComboBox.addItem(i);
}
monthComboBox.setBounds(120, 20, 80, 30);
frame.add(monthComboBox);
JButton showButton = new JButton("Show");
showButton.setBounds(220, 20, 80, 30);
showButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int year = (int) yearComboBox.getSelectedItem();
int month = (int) monthComboBox.getSelectedItem();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int daysOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = 0; i < dayLabels.length; i++) {
dayLabels[i].setText("");
}
for (int i = 1; i <= daysOfMonth; i++) {
dayLabels[firstDayOfWeek + i - 2].setText(String.valueOf(i));
}
}
});
frame.add(showButton);
dayLabels = new JLabel[42];
int x = 20;
int y = 70;
for (int i = 0; i < dayLabels.length; i++) {
dayLabels[i] = new JLabel();
dayLabels[i].setHorizontalAlignment(SwingConstants.CENTER);
dayLabels[i].setBounds(x, y, 40, 30);
frame.add(dayLabels[i]);
x += 40;
if (x > 300) {
x = 20;
y += 30;
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new CalendarGUI();
}
}
```
程序中使用了 `JComboBox` 控件来实现下拉框,分别用来选择年和月。在点击 "Show" 按钮后,程序会根据所选的年、月计算出该月的第一天是星期几,以及该月的天数。然后程序使用一个 `JLabel` 数组来显示当月的日历。
阅读全文