Search code examples
javaswingjcomboboxitemlistener

how can I detect which combobox state changed?


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.


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
       }