class Calendar implements ItemListener{
private static final int s_year = 1970;
private static final int e_year = 2050;
private final JComboBox cboYear;
private final JComboBox cboMonth;
private final JComboBox cboDay;
public Calendar(JComboBox cboYear, JComboBox cboMonth, JComboBox cboDay) {
this.cboYear = cboYear;
this.cboMonth = cboMonth;
this.cboDay = cboDay;
}
/**
* 初始化年月日下来列表框
*/
public void AddInfo() {
//年下拉选择框
for (int i = s_year; i < e_year; i++) {
cboYear.addItem("" + i);
}
//月下拉选择框
for (int i = 0; i < 12; i++) {
cboMonth.addItem("" + (i + 1));
}
//日下拉选择框
for (int j = 0; j < 31; j++) {
cboDay.addItem("" + (j + 1));
}
}
@Override
public void itemStateChanged(ItemEvent e) {
Object obj = cboMonth.getSelectedItem();// 取得选中月份
if (obj != null) {
cboDay.removeAllItems();// 清空日的下拉列表框
int month = Integer.parseInt(obj.toString());
int days = 31;
if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
}
else if (month == 2) {
//取得选中年份
int year = Integer.parseInt(Objects.requireNonNull(cboYear.getSelectedItem()).toString());
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {// 是闰年
days = 29;
}
else {// 不是闰年
days = 28;
}
}
for (int j = 0; j < days; j++) {
cboDay.addItem("" + (j + 1));
}
}
}
}
这是日历类。
cb_year.setSize(100, 50);
cb_month.setSize(100, 50);
cb_day.setSize(100, 50);
cb_year.addItem(null);
cb_month.addItem(null);
cb_day.addItem(null);
calendar.AddInfo();
container.add(cb_year);
container.add(cb_month);
container.add(cb_day);
我在主界面中只会这样实现,我不知道如何调用类中的ItemListener函数来让日期中的日随月份的变化而变化,求解答!