在做Swing开发时,使用三个JComboBox分别表示年月日,而我们要实现的是当改变年份时,2月的天数可以随之改变。或者月份改变时,这个月的天数随之改变。
cb_year = new JComboBox();
jp.add(cb_year);
cb_month = new JComboBox();
jp.add(cb_month);
cb_day = new JComboBox();
jp.add(cb_day);
for(int i = 2011; i>1940; i--)
cb_year.addItem(i);
for(int i = 1; i<=12; i++)
cb_month.addItem(i);
for(int i=1; i<=31;i++)
cb_day.addItem(i);
cb_year.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
JComboBox cb = (JComboBox) evt.getSource();
Object newItem = cb.getSelectedItem();
int days = getDayByYearAndMonth(Integer.parseInt(newItem.toString())
,Integer.parseInt(cb_month.getSelectedItem().toString()));
cb_day.removeAllItems();
for(int i=1; i<=days;i++)
cb_day.addItem(i);
}
});
cb_month.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
JComboBox cb = (JComboBox) evt.getSource();
Object newItem = cb.getSelectedItem();
int days = getDayByYearAndMonth(
Integer.parseInt(cb_year.getSelectedItem().toString())
,Integer.parseInt(newItem.toString())
);
cb_day.removeAllItems();
for(int i=1; i<=days;i++)
cb_day.addItem(i);
}
});
public static int getDayByYearAndMonth(int year,int month)
{
if(month==2)
if((year%4==0&&year%100!=0)||(year%100==0&&year%400==0))
return 29;
else return 28;
else if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
return 31;
else return 30;
}
我对这些不熟,就算是抛砖引玉吧~~