java 如何使用另一个组合框摆动来控制组合框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10367834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:42:47  来源:igfitidea点击:

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

javaswing

提问by lina

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.

我有两个组合框的物品第一个是(女性和男人)。我想要当用户在第一个组合盒中选择女性的女性的衣服列表将出现在第二个组合盒中,当男人被选中时,男装的衣服列表将出现第二个。可以通过使用 JCombo 框来实现这个功能吗?如果是的话,我该怎么做,请举个例子。任何帮助将不胜感激。

回答by tenorsax

Check out how to work with models in How to Use Combo Boxesand How to Use Liststotorials. 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:

如何使用组合框如何使用列表教程中查看如何使用模型。根据第一个组合框中的选择 - 重建、过滤或替换第二个组合框的模型。您可以使用/扩展DefaultComboBoxModel- JComboBox. 例如考虑这个片段:

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 JComboBoxmethods removeAllItems()and addItem().

或者,在第一个组合中选择后,您可以手动重建第二个组合中的项目,即:使用JComboBox方法removeAllItems()addItem()

回答by Eugene Ryzhikov

You have to add event listener to the first combobox. This way you will know when its selection changes, you can interrogate it and fill your second combobox out with appropriate data.

您必须将事件侦听器添加到第一个组合框。这样您就会知道它的选择何时发生变化,您可以查询它并用适当的数据填充第二个组合框。

More information is at http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#listeners

更多信息位于http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#listeners