Java Editable JCombobox Keylistener event for Enter key

孤者浪人 提交于 2019-11-28 12:26:59

Please check if this code helps you!!!

JFrame frame = new JFrame("Welcome!!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JComboBox cmb = new JComboBox();
cmb.setEditable(true);
cmb.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {

    @Override
    public void keyReleased(KeyEvent event) {
        if (event.getKeyChar() == KeyEvent.VK_ENTER) {
            if (((JTextComponent) ((JComboBox) ((Component) event
                    .getSource()).getParent()).getEditor()
                    .getEditorComponent()).getText().isEmpty())
                System.out.println("please dont make me blank");
        }
    }
});
frame.add(cmb);

frame.setLocationRelativeTo(null);
frame.setSize(300, 50);
frame.setVisible(true);

Most people find it difficult because of this casting.

Aqeel Haider

We need to add a key listener on the component that the combo box is using to service the editing.

JTextComponent editor = (JTextComponent) urCombo.getEditor().getEditorComponent();
editor.addKeyListener(new KeyAdapter() {
   public void keyReleased(KeyEvent evt) {
      // your code
   }
});

Hope this code helps.

Note that I can't use Action listener for this.

this doesn't make me any sence, then to use ItemListener

Any idea how to solve this?
  • never to use KeyListener for Swing JComponents, use (Note that I can't use Action listener for this.) KeyBindings instead,

  • notice ENTER key is implemented for JComboBox in API by default, have to override this action from ENTER key pressed

One option would be to replace the KeySelectionManager interface with your own. You want to replace the JComboBox.KeySelectionManager as it is responsible for taking the inputted char and returns the row number (as an int) which should be selected.

vichu

Please check the event ascii code by ev.getkeycode() and check if it is a number or character. If it is neither a number nor a character do nothing. If it is what you want then do the process.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!