Wednesday, January 04, 2012

Using Editable JComboBox with KeyEvent

//The following code wont’t work
JComboBox jcb1 = new JComboBox();
jcb1.setEditable(true);
jcb1.addKeyListener(aKeyEventObject);

//Correct: KeyEvent should be added to JComboBox.getEditor().getEditorComponent()
JComboBox jcb2 = new JComboBox();
jcb2.setEditable(true);
jcb2.getEditor().getEditorComponent().addListerer(aKeyEventObject);

Calling to JComboBox.getEditor().getEditorComponent() will return a JTextField that is used for editing the comboBox’s text.

And if at the same moment you want to get the filling text:

//The following code won’t work(return null)
String s = jcb2.getSelectedItem().toString();

//Correct:
String s = ((JTextComponent)jcb.getEditor().getEditorComponent()).getText();

Comments

0 Responses to "Using Editable JComboBox with KeyEvent"

Post a Comment

Tags