Changing elements of a JComboBox according to the selection from another JComboBox

瘦欲@ 提交于 2020-01-05 03:26:10

问题


I have a small app that generates statistic charts from a MySQL DB via JPA. To select which DB components to include in the statistic I have installed 2 JComboBoxes. First JComboBox is populated with the elements of Category1, second JComboBox with elements from Category2, which is a subcategory of Category1. What i want to do is populate JComboBox2 only with the elements of Category2 that are linked to the selection in JComboBox1.

Example: Category1 is car brands, Category2 is models; I want JComboBox2 to show only the models for the selected brand, right now it shows every available model of every brand.


回答1:


First, add a listener on the 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
    }
}

In order to fill the ComboBox2, you should empty it first

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


来源:https://stackoverflow.com/questions/5336711/changing-elements-of-a-jcombobox-according-to-the-selection-from-another-jcombob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!