使用来自另一个 JComboBox 的选择填充 JComboBox

Populating a JComboBox with a selection from another JComboBox

我有 2 个 JComboBoxes,一个显示类型为 CategoryObjects(每个 Category 包含一个唯一的 List),另一个要显示Category.

中的 List

目的是允许用户在第一个 JComboBox 中 select 一个 Category,然后用 List 适当的 JComboBox 填充第二个 JComboBox给用户 selection.

我当前的代码,在用户 selection 之前,显示第一个 JComboBoxObjectsCategory 类型。第二个显示 Object 中的 List没关系。 但是在用户 selection 上,第二个 JComboBox 什么都不做。它继续在用户 selection.

之前显示相同的 list

这是我的代码..

List<Category> catList = Control.getCatList();
        editItemCatComboBox.removeAllItems();
        for(Category cat: catList) //This populates the 1st JComboBox
        {
            editItemCatComboBox.addItem(cat);

        }
        String selectedCat = editItemCatComboBox.getSelectedItem().toString(); //maybe this line is wrong
        //editItemDialog.validate();
        for (Category cat: catList) //This block should populate the 2nd JComboBox
        {
            if(selectedCat.equals(cat.getCatName()))
            {
                List<Item> itemList = cat.getCatItems();
                editItemItemsComboBox.removeAllItems();
                for(Item itm: itemList)
                {

                    editItemItemsComboBox.addItem(itm);
                }
            }
        }


        editItemDialog.setVisible(true);

我认为您应该在包含类型 Category 的第一个 JCombobox editItemCatComboBox 上实现一个 ItemListener,这样您就可以在每次 select 一个新的 [=12] 时更新第二个=]

editItemCatComboBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent arg0) {
        //Update the second JCombobox
    }
});