3

Here is the scenario: I have a table in database with 3 columns (id, name, age). I've created 3 swing comboboxes and a button that sends a "select statement" to the database and fills the comboboxes out with addItem(...).
Now i wanna know how to link comboboxes such that when I select a value from lets say, the second combobox that fetches "name", the appropriate "age" value appears in the third combobox.

My ActionEvent for the button:

 jComboBox1.addItem(search.getInt("ID"));
 jComboBox2.addItem(search.getString("NAME"));
 jComboBox3.addItem(search.getString("AGE")); 

** search is the ResultSet I acquire!

Thanks in advance.

kevoroid
  • 5,052
  • 5
  • 34
  • 43

1 Answers1

3

You should implement a custom ComboBoxModel for such operations.

You can put the logic of your choices inside setSelectedItem method:

public class YourComboBoxModel implements ComboBoxModel{
    public void setSelectedItem(Object anItem){

    }
    public Object getSelectedItem() {...}
    public Object getElementAt(int index){...} 
    public int getSize() {...}
}

and add the desired ComboBoxModel to the relative JComboBox:

YourComboBoxModel model = new YourComboBoxModel();
JComboBox box = new JComboBox();
box.setModel(model);
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
  • +1 for changing models; `DefaultComboBoxModel` may be sufficient. There's a related example [here](http://stackoverflow.com/questions/3191882). – trashgod Sep 08 '11 at 17:47
  • or http://stackoverflow.com/questions/6261017/how-to-add-different-jcombobox-items-in-a-column-of-a-jtable-in-swing/6261853#6261853, or http://stackoverflow.com/questions/6246005/jcombobox-change-another-jcombobox/6246655#6246655 +1 – mKorbel Sep 08 '11 at 18:04
  • Let me try these and get back to ya! After-all still in the process of learning! Tnx – kevoroid Sep 09 '11 at 05:14