Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to control a combo box by using another combo box swing

Tags:

java

swing

I have two combo box the items first one is (women and men).I want when user select women in first combo box the list of women's dress will appear in second combo box and when men is selected the list of men's dress will appear in second one.Can do this functionality by using JCombo box? if yes how can I do that give me example please. any help will be appreciated.

like image 613
lina Avatar asked Dec 13 '22 03:12

lina


1 Answers

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().

like image 198
tenorsax Avatar answered Jan 18 '23 22:01

tenorsax