【问题标题】:Changing elements of a JComboBox according to the selection from another JComboBox根据来自另一个 JComboBox 的选择更改 JComboBox 的元素
【发布时间】:2011-07-17 05:47:14
【问题描述】:

我有一个小应用程序,它通过 JPA 从 MySQL 数据库生成统计图表。为了选择要包含在统计中的数据库组件,我安装了 2 个 JComboBoxes。第一个 JComboBox 用 Category1 的元素填充,第二个 JComboBox 用 Category2 的元素填充,它是 Category1 的子类别。我想要做的是仅使用与 JComboBox1 中的选择相关联的 Category2 元素填充 JComboBox2。

例如:Category1 是汽车品牌,Category2 是车型;我希望 JComboBox2 仅显示所选品牌的型号,现在它显示每个品牌的所有可用型号。

【问题讨论】:

    标签: java swing jcombobox


    【解决方案1】:

    首先,在 Combobox1 上添加一个监听器:

    private void comboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {                                                     
    
        if (java.awt.event.ItemEvent.DESELECTED == evt.getStateChange()) {
    
            String valueBeforeDeselection = evt.getItem().toString();
            // Do something if needed
    
        } else if (java.awt.event.ItemEvent.SELECTED == evt.getStateChange()) {
    
            String valueAfterSelection = evt.getItem().toString();
            // Set the values of the ComboBox2
        }
    }
    

    为了填充 ComboBox2,你应该先清空它

    comboBox2.removeAllItems();
    comboBox2.addItem("Value 1");
    comboBox2.addItem("Value 2");
    

    【讨论】:

      猜你喜欢
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多