Detecting when user presses enter in Java

后端 未结 2 740
天涯浪人
天涯浪人 2021-01-18 07:14

I have a subclass of JComboBox. I attempt to add a key listener with the following code.


        addKeyListener(new KeyAdapter() 
        {
            pub         


        
2条回答
  •  太阳男子
    2021-01-18 07:30

    Key events aren't fired on the box itself, but its editor. You need to add the keyListener to the editor of the JComboBox and not the box directly:

    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() 
        {
            public void keyPressed(KeyEvent evt)
            {
                if(evt.getKeyCode() == KeyEvent.VK_ENTER)
                {
                    System.out.println("Pressed");
                }
            }
        });
    

    Edit: fixed method call.

提交回复
热议问题