年月日下拉列表,比较繁琐,做成一个可重用的类,以后可以直接使用。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
public class YearMonthDay implements ItemListener{
private int STARTYEAR = 1950;
private int ENDYEAR = 2010;
private JComboBox cboYear;
private JComboBox cboMonth;
private JComboBox cboDay;
/**
* 传入年月日下拉列表框组件
* @param cboYear
* @param cboMonth
* @param cboDay
*/
public YearMonthDay(JComboBox cboYear, JComboBox cboMonth, JComboBox cboDay) {
this.cboYear = cboYear;
this.cboMonth = cboMonth;
this.cboDay = cboDay;
}
/**
* 初始化年月日下来列表框
*/
public void AddInfo() {
//年下拉选择框
for (int i = STARTYEAR; i < ENDYEAR; 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));
}
}
/**
* 月 下拉框监听事件
* @author Vecrates
*
*/
@Override
public void itemStateChanged(ItemEvent e) {
Object obj = cboMonth.getSelectedItem();// 取得选中月份
if (obj != null) {
cboDay.removeAllItems();// 清空日的下拉列表框
int month = Integer.valueOf(obj.toString());
int days = 31;
if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
}
else if (month == 2) {
//取得选中年份
int year = Integer.parseInt(cboYear.getSelectedItem()
.toString());
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
// 是闰年
days = 29;
}
else {
// 不是闰年
days = 28;
}
}//if
for (int j = 0; j < days; j++) {
cboDay.addItem("" + (j + 1));
}//for
}//if
}
}