This discussion is archived
1 Reply Latest reply: Mar 25, 2013 11:11 AM by KonradZuse RSS

How can achieve Enter key pressed functionality on ComboBox.

Rahul1981 Newbie
Currently Being Moderated
Hi All,


I am using the following code

libraryCombo.setOnKeyPressed(new EventHandler<KeyEvent>(){
@Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
btn_OkAction.requestFocus();
makeOKAction(null);
}
}
});

Where libraryCombo is the object of ComboBox

But this code is not working for Enter Key but for Other Keys it os working properly.

I also tried this but has the same behavior

libraryCombo.getEditor().addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>(){
@Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
btn_OkAction.requestFocus();
makeOKAction(null);
}
}
});

Please help How can I achieve Enter key pressed functionality on ComboBox.
  • 1. Re: How can achieve Enter key pressed functionality on ComboBox.
    KonradZuse Explorer
    Currently Being Moderated
    your issue IMO is keyEvent.getCode() What you are returning is a KeyCode, not what key it is. If you have issues, try using a System.out.println();

    What I use for my Mouse and Key events is
    event.getEventType() == MouseEvent.MOUSE_DRAGGED
    so just switch from MouseEvent to KeyEvent and it should all work.

    Lets look at the API http://docs.oracle.com/javafx/2/api/javafx/scene/input/KeyEvent.html
    getCode
    public final KeyCode getCode()
    The key code associated with the key in this key pressed or key released event. For key typed events, code is always KeyCode.UNDEFINED.
    Returns:
    The key code associated with the key in this event, KeyCode.UNDEFINED for key typed event
    Your KeyEvents are
    Field Summary
    
    Fields 
    Modifier and Type     Field and Description
    static EventType<KeyEvent>     ANY
    Common supertype for all key event types.
    static java.lang.String     CHAR_UNDEFINED
    KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character use this for the keyChar value.
    static EventType<KeyEvent>     KEY_PRESSED
    This event occurs when a key has been pressed.
    static EventType<KeyEvent>     KEY_RELEASED
    This event occurs when a key has been released.
    static EventType<KeyEvent>     KEY_TYPED
    This event occurs when a key has been typed (pressed and released).
    The important getEventType() is inherited from Event http://docs.oracle.com/javafx/2/api/javafx/event/Event.html#getEventType()


    It can also be found in the KeyChar API right under the "Method Summary."
    getEventType
    public EventType<? extends Event> getEventType()
    Gets the event type of this event. Objects of the same Event class can have different event types. These event types further specify what kind of event occurred.
    Returns:
    the event type

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points