How do I pick up the Enter Key being pressed in JavaFX2?

Geesh_SO picture Geesh_SO · Dec 14, 2012 · Viewed 79.3k times · Source

I have a TextField to enter a search term, and a button for "Go". But in JavaFX2, how would I make it so pressing the Enter Key in the TextField would perform an action?

Thanks :)

Answer

Brendan picture Brendan · Dec 14, 2012

I'm assuming you want this to happen when the user presses enter only while the TextField has focus. You'll want use KeyEvent out of javafx.scene.input and do something like this...

textField.setOnKeyPressed(new EventHandler<KeyEvent>()
    {
        @Override
        public void handle(KeyEvent ke)
        {
            if (ke.getCode().equals(KeyCode.ENTER))
            {
                doSomething();
            }
        }
    });

Hope this is helpful!