开发者

add ListSelectionListener on JComboBox

I'm quite new to Java Swing. And I'm stuck on trying to add a ListSelectionListener on a JComboBox instance. It seems only the ListSelectionModel interface has addListSelectionListener method. I kind of cannot figure it out...

Why I want to do add it is that I want program do something even the ite开发者_Go百科m in the combo box is not changes after selecting.

POTENTIAL ANSWER I was simply thinking of attaching an actionListener on combobox not working. and i think it's bug of openjdk. I've reported it here

Thanks in advance.


Take a look at JComboBox#addItemListener:

JComboBox combo = createCombo();
combo.addItemListener(new ItemListener()
{
    @Override
    public void itemStateChanged(ItemEvent e)
    {
        if (e.getStateChange() == ItemEvent.SELECTED)
        {
            Object selectedItem = e.getItem();
            // Do something with the selected item...
        }
    }
});

This event is fired for both mouse and keyboard interaction.


For JComboBox, you'll have to use ActionListener.

    JComboBox jComboBox = new JComboBox();
    jComboBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("combobox event");

        }
    });

AFAIK, actionPerformed is raised whenever the user makes a selection for the JComboBox even if it's the same item that was already selected.


It depends on your requirement. The ActionEvent is only fired when the keyboard is used, not when the selection changes as the mouse is moved over the items.

If you want to do some action when the item selection changes even if the mouse is moved then yes you will probably need access to the JList. You can access the JList used by the popup with the following code:

JComboBox comboBox = new JComboBox(...);
BasicComboPopup popup = (BasicComboPopup)comboBox.getAccessibleContext().getAccessibleChild(0);
JList list = popup.getList();
list.addListSelectionListener(...);


Use a PopupMenuListener. When the popup menu closes get the selected index and do your processing.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜