I’m working on a desktop (swing) application with Eclipse IDE. I have three comboboxes (countries, states and cities) and I need to update the data automatically when I selecting a new country or province. I searched lot of information, but all the implementations I found are made on Ajax or the beansbinding framework in NetBeans.
I tried a solution by ItemEvent, but I have problems starting my application it loads the list of countries but not the other lists. And by selecting a country is charged the list of states but not the list of cities.
My code:
jComboBoxCountries.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxStates.setModel(new javax.swing.DefaultComboBoxModel(
statesOf(evt.getItem()).toArray() ));
}
});
jComboBoxStates.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxCities.setModel(new javax.swing.DefaultComboBoxModel(
citiesOf(evt.getItem()).toArray()) );
}
});
jComboBoxCountries.setModel(new javax.swing.DefaultComboBoxModel(
countryList.toArray()));
It seems like you have to specifically set the selected index to invoke the listener.
I would guess this is the same problem, once you reset the model of the states combobox you would need to select its index as well.
Another approach is to not select a default state or city, but instead prompt the user to select one. Here is some code that uses this approach: