Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Editable JCombobox Keylistener event for Enter key

I have editable JCombobox and I added keylistener for combobox editor component. When user press 'Enter key' and if there is no text on the editable combobox I need to display message box using JOptinoPane. I have done necessary code in keyrelease event and it displays message as expected.

Problem is, when we get message box and if user press enter key on 'OK' button of JOptionPane, combobox editor keyevent fires again. Because of this, when user press Enter key on message box, JoptionPane displays continuously.

Any idea how to solve this?

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

like image 675
Joe Avatar asked Dec 27 '12 14:12

Joe


2 Answers

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.

like image 188
Chand Priyankara Avatar answered Oct 18 '22 21:10

Chand Priyankara


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.

like image 23
Aqeel Haider Avatar answered Oct 18 '22 19:10

Aqeel Haider