Check out how to work with models in How to Use Combo Boxes and How to Use Lists totorials. According to a selection in the first combo box – rebuild, filter or perhaps replace the model of the second combo box. You can use/extend DefaultComboBoxModel – a default model used by a JComboBox
. For example consider this snippet:
final JComboBox genderComboBox = null;
final JComboBox itemComboBox = null;
final DefaultComboBoxModel hisModel = new DefaultComboBoxModel(new String[]{"a", "b", "c"});
final DefaultComboBoxModel herModel = new DefaultComboBoxModel(new String[]{"x", "y", "z"});
genderComboBox.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
if ("Men".equals(genderComboBox.getSelectedItem())){
itemComboBox.setModel(hisModel);
} else {
itemComboBox.setModel(herModel);
}
}
});
Alternatively, upon selection in the first combo you can rebuild the items in the second one manually, ie: using JComboBox
methods removeAllItems()
and addItem()
.