Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

java - how to control a combo box by using another combo box 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...