检查此代码
public class ComboBoxDatePicker extends JPanel implements ItemListener {
private static final long serialVersionUID = 1L;
private JComboBox myDay;
private JComboBox myMonth;
private JComboBox myYear;
private Collection<ItemListener> myListeners;
public ComboBoxDatePicker(String name) {
this(name, new Date(System.currentTimeMillis()));
}
public ComboBoxDatePicker(String name, Date date) {
super(new FlowLayout(FlowLayout.LEFT));
myListeners = new HashSet<ItemListener>();
myDay = new JComboBox(new RangeModel(1, 31));
myMonth = new JComboBox(new RangeModel(1, 12));
myYear = new JComboBox(new RangeModel(2000, 2020));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
myDay.setSelectedItem(calendar.get(Calendar.DAY_OF_MONTH));
myMonth.setSelectedItem(calendar.get(Calendar.MONTH) + 1);
myYear.setSelectedItem(calendar.get(Calendar.YEAR));
myDay.addItemListener(this);
myMonth.addItemListener(this);
myYear.addItemListener(this);
add(new JLabel(name));
add(myDay);
add(myMonth);
add(myYear);
doLayout();
}
public void setEnabled(boolean enabled) {
myDay.setEnabled(enabled);
myMonth.setEnabled(enabled);
myYear.setEnabled(enabled);
}
public Date getDate() {
if (!myDay.isEnabled()) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.DAY_OF_MONTH, (Integer) myDay.getSelectedItem());
calendar.set(Calendar.MONTH, (Integer) myMonth.getSelectedItem() - 1);
calendar.set(Calendar.YEAR, (Integer) myYear.getSelectedItem());
return calendar.getTime();
}
private static class RangeModel implements ComboBoxModel {
private int myMin;
private int myMax;
private Object mySelection;
public RangeModel(int min, int max) {
myMin = Math.min(min, max);
myMax = Math.max(min, max);
mySelection = myMin;
}
public Object getSelectedItem() {
return mySelection;
}
public void setSelectedItem(Object anItem) {
mySelection = anItem;
}
public int getSize() {
return myMax - myMin + 1;
}
public Object getElementAt(int index) {
return myMin + index;
}
public void addListDataListener(ListDataListener l) {
}
public void removeListDataListener(ListDataListener l) {
}
}
public void addItemListener(ItemListener l) {
myListeners.add(l);
}
public void itemStateChanged(ItemEvent e) {
for (ItemListener listener : myListeners) {
listener.itemStateChanged(e);
}
}
}
你可以在任何需要的地方使用它
JFrame frame = new JFrame() ;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ComboBoxDatePicker chooser = new ComboBoxDatePicker("Choose Date");
frame.add(chooser);
frame.pack();
frame.setVisible(true);