4

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第二个。可以通过使用 JCombo 框来实现此功能吗?如果是的话,我该怎么做,请给我一个例子。任何帮助将不胜感激。

4

2 回答 2

12

如何使用组合框如何使用列表中查看如何使用模型。根据第一个组合框中的选择 - 重建、过滤或替换第二个组合框的模型。您可以使用/扩展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);    
        }
    }
});

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

于 2012-04-28T22:26:15.217 回答
1

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

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

于 2012-04-28T21:52:15.013 回答