且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用另一个组合框swing来控制组合框

更新时间:2023-01-13 15:21:10

查看如何使用如何使用组合框如何使用使用列表 totorials。根据第一个组合框中的选择 - 重建,过滤或替换第二个组合框的模型。您可以使用/扩展 DefaultComboBoxModel - 的JComboBox 。例如,请考虑以下代码段:

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);    
        }
    }
});

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

Alternatively, upon selection in the first combo you can rebuild the items in the second one manually, ie: using JComboBox methods removeAllItems() and addItem().