How do I pick up the Enter Key being pressed in Ja

2019-02-11 18:17发布

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 :)

6条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-11 18:41

You can use the onAction attribute of the TextField and bind it to a method in your controller.

@FXML
public void onEnter(ActionEvent ae){
   System.out.println("test") ;
}

And in your FXML file:

<TextField fx:id="textfield" layoutX="29.0" layoutY="298.0" onAction="#onEnter" prefWidth="121.0" />
查看更多
The star\"
3楼-- · 2019-02-11 18:47

Simply using "lambda expression" :

TextField textField = new TextField();
textField.setOnAction(e -> {
    // add your code to be run here
    System.out.println("textFile");
    });
查看更多
孤傲高冷的网名
4楼-- · 2019-02-11 19:01

On some keyboards you have to put additional tests to the '\n' and '\r' characters.

if(event.getCode().equals(KeyCode.ENTER) || event.getCharacter().getBytes()[0] == '\n' || event.getCharacter().getBytes()[0] == '\r') {
        // your action
    }
查看更多
小情绪 Triste *
5楼-- · 2019-02-11 19:02

This works:

@FXML public TextField txt;

@FXML
public void textAction(KeyEvent e){

    if(e.getCode().equals(KeyCode.ENTER))
        System.out.println(txt.getText());
}

If for some reason .getCode() is not working, make sure you import the library:

import javafx.scene.input.KeyEvent;

NOT

import java.awt.event.KeyEvent;

I got caught up on this and it was irritating. Im just passing this on for all those in the same boat.

查看更多
爷、活的狠高调
6楼-- · 2019-02-11 19:06

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!

查看更多
smile是对你的礼貌
7楼-- · 2019-02-11 19:07

You can try the following:

@FXML
public void buttonPressed(KeyEvent e)
{
    if(e.getCode().toString().equals("ENTER"))
    {
        //do something
    }
}
查看更多
登录 后发表回答