开发者

Java: myComboBoxItemStateChanged is triggered twice?

I've placed a JComboBox on a JDialog, then by NetBeans desig开发者_运维百科n view, I bind the JComboBox to an event function Events > Item > itemStateChanged

private void myComboBoxItemStateChanged(ItemEvent evt) {//created by netbeans
     System.out.println("triggered");
}

when I change the comboBox by myComboBox.setSelectedIndex(#), it's calling the myComboBoxItemStateChanged() Once, but if I change it by clicking on the comboBox and selecting another item, it triggers myComboBoxItemStateChanged() twice! it prints "triggered" twice?

This issue is happening in all of my comboboxes!

What am I doing wrong? or is it a bug?


That is because one event is to tell the listener that one option has been deselected, and the next event to tell that another option has been selected.

You can figure out what an event actually refers to by calling evt.getStateChange(). It will return either ItemEvent.SELECTED or ItemEvent.DESELECTED.

If you change "triggered" to "triggered " + evt.getStateChange() you'd see the difference as it would print

triggered 2
triggered 1

So, if you're only interested in events where something has been selected you could add, to the top of your listener implementation

if (evt.getStateChange() == ItemEvent.DESELECTED)
    return;

Here's a snippet from the docs on getStateChange():

Returns the type of state change (selected or deselected).

Returns: an integer that indicates whether the item was selected or deselected


You can do it like this:

jComboBox.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                        System.out.println("triggered");
                }
        });

It print(triggered) once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜