I have to two comboboxes, based on the selection made in the first combobox the selected value of the second box should change. Please find the code snippet below:
secondcombobox.setSelectedItem(firstcombobox.getSelectedItem());
I have to two comboboxes, based on the selection made in the first combobox the selected value of the second box should change. Please find the code snippet below:
secondcombobox.setSelectedItem(firstcombobox.getSelectedItem());
Although your minimal question length makes your question cryptical, you will probably need:
firstcombobox.addActionListener() {
// Do something with secondcombobox
}
You should use an ActionListener:
firstcombobox.addActionListener(new ActionListener(){
void actionPerformed(ActionEvent e){
// sets the selected item of secondcombobox to be the value of firstcombobox
// assuming secondcombobox contains such a value.
secondcombobox.setSelectedItem(firstcombobox.getSelecteditem());
}
});
Note scoping here is important. You can either make firstcombobox
and secondcombobox
global or final, or you can use a slightly alternate form where you take those arguments as inputs to a constructor:
firstcombobox.addActionListener(new ActionListener(firstcombobox, secondcombobox){
private JComboBox a;
private JComboBox b;
public ActionListner(JComboBox a, JComboBox b){
this.a = a;
this.b = b;
}
void actionPerformed(ActionEvent e){
// sets the selected item of a to be the value of b
// assuming a contains such a value.
b.setSelectedItem(a.getSelecteditem());
}
});
Your code above will only work if the selected item in the first JComboBox
also exists in the second JComboBox
; In other words there exists an object in the second ComboBoxModel
returns true
when compared to the selected item from the first JComboBox
.
If the selected item is not in the list, the method call will have no effect, which is suspect is what's happening in your case.
If your two comboboxes share the same values, you should use the same model for them both. It would be cleaner than to use an ActionListener.
DefaultComboBoxModel model = new DefaultComboBoxModel();
combo1.setModel(model);
combo2.setModel(model);
//init your values in the combo here
Then, when you select an item in one of the comboBoxes, it will be selected in the other.