问题
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