Search code examples
javaswingbindingjcomboboxitemlistener

Binding two JComboBoxes


I have a HashMap that looks like this:

HashMap<CauseCategory, ArrayList<Cause>> data;

CauseCategory and Cause are just classes with one string instance fields in them, set by their constructors or setter methods (if needed). Now, the system fetches a bunch of cause categories from the database, and for each cause catagory there are a number of causes associated with it.

Say we have a cause category "technical", it would have multiple causes associated with it, such as "packaging problem", "processing error", "miscalculation error", and so on.

I feed my GUI class this HashMap, which has two JComboBoxes (Cause Categories + Cause Descriptions).

How can I bind the first combobox (categories) so that when I select one item from that list, it only shows the causes associated with it in the second combobox (cause descriptions)?

EDIT: It may be simplier to think of the hashmap like this:

HashMap<String, ArrayList<String>> data;

Solution

  • Add an ActionListener to the first combo box. Each time the selection changes, an ActionEvent will be fired and the ActionListener will thus be invoked. From the listener, get the newly selected category from the combo box, then get the associates causes from the Map, and change the items displayed in the second combo box.

    As usual: link to the swing tutorial.