Search code examples
javaswingjcomboboxactionlistener

Actionperformed not triggered for JComboBox


I have an ActionListener attached to a JComboBox(uneditable). Once an item from the JComboBox is selected, I have to make the next button in the frame visible.

The skeleton of the code looks like this:

public void actionPerformed(ActionEvent evt)
{
    if(evt.getSource()==jComboBox){
        if(jComboBox.getSelectedIndex()==-1)
            //Display an alert message

        else{
            nextButton.setVisible(true);
        //Do other actions
        }
    }
}

It is found that actionPerformed is called only when the second, third, fourth (and so on) items are selected. But actionPerformed is not called when the first item is selected the very first time. But if the first item is selected after selecting other items actioPerformed gets called and the code works fine.

This error appears on some systems and doesn't on other systems. Any help in this regard would be appreciated.

Thanks in Advance!!


Solution

  • This is the normal behavour. The ActionEvent is not fired when you reselect the same item. If you want the event to be fired when you create the combo box then your code should be something like:

    JComboBox comboBox = new JComboBox(...);
    comboBox.setSelectedIndex(-1); // remove automatic selection of first item
    comboBox.addActionListener(...);
    comboBox.setSelectedIndex(0);
    

    or

    JComboBox comboBox = new JComboBox();
    comboBox.addActionListener(...);
    comboBox.addItem(...);
    comboBox.addItem(...);