简体   繁体   中英

How to Call same method for mouse click event and enter key press in javafx

@FXML
private void login(Event event) throws IOException {
    String userName = emailId.getText().trim();
    String password = passwordId.getText().trim();

    try {
        if(isValidCredentials(userName, password)){
            System.out.println("Login Successfull");
            Parent mainScreen = FXMLLoader.load(getClass().getResource("MainPage.fxml"));
            Scene mainScene = new Scene(mainScreen);
            Stage mainStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
            mainStage.hide();
            mainStage.setScene(mainScene);
            mainStage.setTitle("Main Screen");
            mainStage.show();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

This login method is being called on mouse click of login button. What i want is same method to be called when enter key is pressed on login page.

You can make the login button the default button: that way it will fire action events when the enter key is pressed:

<Button fx:id="loginButton" text="Login" onAction="#login" defaultButton="true" />

This will work unless a control that consumes an Enter key press has the keyboard focus, which is likely what you need. If you also have text fields, for example, and you want the login action to be performed when the enter key is pressed on those text fields, just set the onAction handler for the text fields as well:

<TextField fx:id="emailId" onAction="#login" />

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