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();
}
}
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: