Reputation: 374
I have two JComboBox
in a form and I added an ItemListener
to them and I should overwrite itemStateChanged()
, now I wanna say if the first JComboBox
items selected do something and else if the second JComboBox
items selected do another thing, but I don't know how? Maybe code can help you.
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==ItemEvent.SELECTED)
picture.setIcon(pics[box.getSelectedIndex()]);
}
In the second line of code I don't know how to recognize which JComboBox
state has changed.
Upvotes: 2
Views: 2358
Reputation: 14413
You can use ItemEvent#getSource()
Example:
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JComboBox){
JComboBox combo = (JComboBox) e.getSource();
//rest of code
}
Now for distinct combo1
from combo2
, you have 2 options , you can set names to that components like this.
combo1.setName("combo1");
combo2.setName("combo2");
And in the itemListener
if(e.getSource() instanceof JComboBox){
JComboBox combo = (JComboBox) e.getSource();
if("combo1".equals(combo.getName())){
// your code
}
.
.// rest of code
}
Or if you know that they are the same instance, then you can always use ==
.
if(combo1 == e.getSource() ){
// your code
}else if (combo2 == e.getSource()){
//code for combo 2
}
Upvotes: 3
Reputation: 41188
There are two ways to do that, the first is to check the source on the event object and see which combo box it matches to.
The alternative is to add a different listener into each combo box, then you know that any calls going into one listener are from the corresponding control. This is a good use for an anonymous inner class.
Upvotes: 2