key listener on combobox

I'm trying to put a keylistener on a JComboBox in a modal JDialog, and am not having any success.

JDialog jd =new JDialog(someParent,"some title",true);

JComboBox jcb =new JComboBox(someVector);

jcb.setEditable(true);

jcb.addKeyListener(new KeyAdapter(){

publicvoid keyPressed(KeyEvent ke){

System.out.println(ke.getKeyCode());

}

});

jd.getContentPane().add(jcb);

This doesn't work. Can anybody tell me why?

Thanks in advance,

m

[892 byte] By [wywiwyg] at [2007-9-26 3:26:25]
# 1

The keystroke is being processed by the root pane container and focus manager before it actually gets to your component.

Remember that in the lightweight component world, your combobox is only an imaginary component drawn on the content pane...

Mitch Goldstein

Author, Hardcore JFC (Cambridge Univ Press)

mdgoldstein@hotmail.com

mitchg at 2007-6-29 11:48:08 > top of Java-index,Archived Forums,Swing...
# 2

I emailed a friend of mine regarding this, and he replied:

vincent dupont wrote:

the actionListener seems to be the way...

it will react to 'enter' key press

see :

http://forums.java.sun.com/thread.jsp?forum=57&thread=123635

if you want more, maybe it will be possible to get the JTextField used for

entering new values into the combo with :

public ComboBoxEditor getEditor()

you should better check if this is really a JtextField, I'm not sure...

and inside the ComboBoxEditor, there is a :

public Component getEditorComponent()

I guess this shoud return the JTextField on which yoiu can get the Document

(JTextComponent.getDocument()).

then you can add a DocumentListener on that Document

JTextComponent textField =

(JTextComponent)(combo.getEditor().getEditorComponent());

textFiled.getDocument().addDocumentListener(new DocumentListener(){

public void changedUpdate(DocumentEvent e) {}

public void insertUpdate(DocumentEvent e) {}

public void removeUpdate(DocumentEvent e) {}

}

);

I'll have a look at my O'Reilly 'Swing' book tonight...

vincent

-- end quote --

I then used jComboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {}) and it works perfect.

theComboBox.getEditor().getEditorComponent().addKeyListener(new KeyListener() {

public void keyTyped(KeyEvent ke) {

if(ke.getKeyCode() == KeyEvent.VK_ENTER)

okButton.doClick();

if(ke.getKeyCode() == KeyEvent.VK_ESCAPE)

cancelButton.doClick();

}

}

wywiwyg at 2007-6-29 11:48:08 > top of Java-index,Archived Forums,Swing...