Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing combo box selection and link to other combo boxes

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.

like image 900
kevoroid Avatar asked Mar 09 '26 16:03

kevoroid


1 Answers

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);
like image 53
Heisenbug Avatar answered Mar 12 '26 23:03

Heisenbug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!