Logical Fallacy
Logical Fallacy

Reputation: 3107

How to fire itemStateChanged event when setting the item's initial value?

I've implemented a java.awt.event.ItemListener that responds to itemStateChanged. It seems to execute as expected for changes to JComboBox However, the event does not fire for the first value that I assign to the combo box.

I couldn't find a way to run this on ideone.com, but the code below can be compiled and executed as-is. Put it in "MyDialog.java," compile with javac.exe *.java and execute with java MyDialog. The DoStuff method will not be executed when the dialog initializes. When the user changes the combo box, however, the event will fire.

import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JDialog;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;

public class MyDialog extends JDialog
{   
    public static void main(String[] args)
    {
        MyDialog dlg = new MyDialog();
        dlg.setVisible(true);
    }

    class MyListener implements java.awt.event.ItemListener
    {
        public void itemStateChanged(ItemEvent event)
        {
            if (event.getSource() == myComboBox &&
                event.getStateChange() == ItemEvent.SELECTED )
            {
                DoStuff(event);
            }
        }
    }

    JComboBox myComboBox;

    public MyDialog()
    {
        this.setSize(100,100);

        myComboBox = new JComboBox();
        myComboBox.addItem("Option 1");
        myComboBox.addItem("Option 2");
        this.add(myComboBox);

        MyListener listener = new MyListener();
        myComboBox.addItemListener(listener);

        myComboBox.setSelectedItem("Option 1");

        // EXPECT: DoStuff() was executed
        // GOT: DoStuff() was not executed
    }

    public void DoStuff(java.awt.event.ItemEvent event)
    {
        JOptionPane.showMessageDialog(null, "DoStuff() was reached.");
    }
}

How do I get the DoStuff event to fire when the dialog initializes?

Upvotes: 1

Views: 3840

Answers (1)

K139
K139

Reputation: 3669

It's because "Option 1" is default/selected option already, that's why

 myComboBox.setSelectedItem("Option 1");

will not trigger any Item changed event. Change the code to

 myComboBox.setSelectedItem("Option 2");

and it will trigger the doStuff() method, because item is indeed changed from current selection.

Upvotes: 1

Related Questions