简体   繁体   中英

Run same function when clicking and pressing enter key

I have this function that runs when clicking on a button, but I want to run the same function when pressing enter. How should I do this?

@FXML
public void login(ActionEvent event) throws IOException {
    if(txtUName.getText().equals("jesse") && txtPass.getText().equals("essej")){
        Parent home;
        try {
            home = FXMLLoader.load(getClass().getResource("Home.fxml"));
            Scene homeScene = new Scene(home);

            Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();

            window.setScene(homeScene);

            window.show();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }else {
        lblError.setVisible(true);
    }
} 

You need a key event, this event should then be check it is "enter" which was pushed.

Detecting when user presses enter in Java

You mean you have another @FXML function that you want to do the same? Just put your logic in a separate function and call it from your event functions.

@FXML
public void buttonPressed(MouseEvent event) {
    doSomething(event);
}

@FXML
public void keyPressed(KeyEvent event) {
    doSomething(event);
}

private void doSomething(InputEvent event) {
    // your code here
}

This KeyEvent and MouseEvent inherit from InputEvent . You can still call .getSource() because it's inherited and in the code you've shown there is nothing more specific you do with the event.

I found a working solution for me.

You can set the button as a Default Button in Scene Builder so when you press enter it also activates the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM