0

I have a method which is called at a event of a value change in a JComboBox

public void actionPerformed( ActionEvent e )
{
    Object source = e.getSource();
    if( source.equals( listComboBox ) )
    {
        changeList();
    }
}


public void changeList()
{ //do some stuff
.....
.....
//warn the user
}

My problem is that this method is called at the initial load method as well. In the method there is a warning message pop up. Which is only needed when the user is changing the selected value of the combo box.(Not when i set a value from the code at the loading method.)

Is there a way(flag,different method) to distinguish between these to actions and give the warning message only when its needed?

direndd
  • 642
  • 2
  • 16
  • 47
  • Possible duplicate of [Java JComboBox listen a change selection event](https://stackoverflow.com/questions/17576446/java-jcombobox-listen-a-change-selection-event) – Arnaud Oct 06 '17 at 13:46

2 Answers2

1

My problem is that this method is called at the initial load method as well.

So add the listener to the combo box AFTER the load is finished.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

You have two options. The first one is to apply a unique listener to each component and handle the event differently ( Which I prefer in most cases cause it keeps code simple for each component and way better to read).

The Second one is to identify which component trigger the event. One way to check that is by taking the sources of the event and check if it matches with the actual object or you can just check if it is 'instanceof' JComboBox and then handle the event as you pleased.

if(sourceObject == myComboBox ){ 
    // handle the event 
}

or

if(sourceObject instanceof JComboBox{
   // then we are dealing with a combobox
   // if it's the only one then you know what to do..
}
JKostikiadis
  • 2,847
  • 2
  • 22
  • 34