Question

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.

Was it helpful?

Solution

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
   }

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top