简体   繁体   English

如何在javafx中为鼠标单击事件调用相同的方法并输入按键

[英]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. 我想要的是在登录页面上按Enter键时要调用的相同方法。

You can make the login button the default button: that way it will fire action events when the enter key is pressed: 您可以将登录按钮设置为默认按钮:这样,当按下Enter键时,它将触发操作事件:

<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. 除非使用Enter键的控件具有键盘焦点(这很可能是您所需要的),否则它将起作用。 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: 例如,如果您还具有文本字段,并且希望在这些文本字段上按Enter键时执行登录操作,则只需为文本字段设置onAction处理程序即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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