Editable JComboBox KeyPressed not working

1.4k views Asked by At


I have this code where I designed an editable JComboBox to listen to my keyPressed event and show a message that the key is pressed. But I have no idea why this not working. As a beginner I might have gone wrong logically/conceptually.

So, I would request for suggestions about how to construct the code, so that it works.

Code

import javax.swing.*;
import java.awt.*;

public class testEJCBX extends JFrame {
    JComboBox jcbx = new JComboBox();

    public testEJCBX() {
        super("Editable JComboBox");
        jcbx.setEditable(true);

        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(jcbx);

        jcbx.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) 
            {
                jcbxKeyPressed(evt);
            }
        });

        setSize(300, 170);
        setVisible(true);
    }
    private void jcbxKeyPressed(java.awt.event.KeyEvent evt) {                                      
       JOptionPane.showMessageDialog(null, "Key Pressed");
    }

    public static void main(String argv[]) {
        new testEJCBX();
    }
}
1

There are 1 answers

4
Hovercraft Full Of Eels On BEST ANSWER

You shouldn't be using a KeyListener for this sort of thing. Rather if you want to detect changes to the combo box's editor component, extract it and add a DocumentListener to it:

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import java.awt.*;

public class TestEJCBX extends JFrame {
   JComboBox<String> jcbx = new JComboBox<>();

   public TestEJCBX() {
      super("Editable JComboBox");
      setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      jcbx.setEditable(true);

      getContentPane().setLayout(new FlowLayout());
      getContentPane().add(jcbx);

      JTextField editorComponent = (JTextField) jcbx.getEditor()
            .getEditorComponent();

      Document doc = editorComponent.getDocument();
      doc.addDocumentListener(new DocumentListener() {

         @Override
         public void removeUpdate(DocumentEvent e) {
            System.out.println("text changed");
         }

         @Override
         public void insertUpdate(DocumentEvent e) {
            System.out.println("text changed");
         }

         @Override
         public void changedUpdate(DocumentEvent e) {
            System.out.println("text changed");
         }
      });

      pack();
      setLocationRelativeTo(null);
      setVisible(true);
   }

   public static void main(String argv[]) {
      new TestEJCBX();
   }
}