Search code examples
javaswingsearchkeyboardjcombobox

Handling actionPerformed on JComboBox only when user confirmed selection


When I register ActionListener on a non-editable JComboBox it fires actionPerformed() every time user changes selected item with arrows keys or with context search (typing the first letter of the item name).

I found similar question here: How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard. But that solution doesn't cover context search option. It fires actionPerformed() when I type something.

How to determine when user confirms selected item using enter key or mouse click?


Solution

  • better would be implements ItemListener (fired twice SELECTED and DESELECTED), than ActionListener and KeyBindings, maybe with succes this simple example here

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.PopupMenuEvent;
    import javax.swing.event.PopupMenuListener;
    
    public class PopupTest {
    
        public static void main(String[] args) {
            final JComboBox c = new JComboBox();
            c.addPopupMenuListener(new PopupMenuListener() {
    
                @Override
                public void popupMenuCanceled(PopupMenuEvent e) {
                    System.out.println(e.getSource());
                }
    
                @Override
                public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                    System.out.println(e.getSource());
                }
    
                @Override
                public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                    System.out.println(e.getSource());
                }
            });
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            f.getContentPane().setLayout(new FlowLayout());
            f.getContentPane().add(c);
            f.pack();
            f.setVisible(true);
        }
    
        private PopupTest() {
        }
    }