【问题标题】:Javafx: How to bound two functions of one buttonJavafx:如何绑定一个按钮的两个功能
【发布时间】:2016-12-18 02:08:39
【问题描述】:

大家好,今天又遇到一个问题。 这是我的代码的一部分。我有 2 个功能要分配给一个按钮(登录),我该怎么做?

@FXML
private void fireLogIn()
{
    LogInButton.setOnKeyPressed(event -> {
           if(event.getCode() == KeyCode.ENTER){
             LogIn(event); // <--- there is an error of wrong type of data 
           }
        }); 
}


@FXML
private void LogIn(ActionEvent event) throws IOException {
    if(LoginField.getText().equals("MKARK")&&PasswdField.getText().equals("KACZOR1"))
    {
        Parent parent = FXMLLoader.load(getClass().getResource("/fxmlFiles/MainScreen.fxml"));
        Scene MainScene = new Scene(parent);
        Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        stage.setScene(MainScene);
        stage.show();


    }
    else
    {
        IncorrectDataLink.setVisible(true);
        IncorrectDataLink.setOnAction(e-> openWebpage(uri));    
}

}

我想同时提供这两种功能,用鼠标按下按钮,或者当它专注于它时按下“ENTER”按钮。

【问题讨论】:

  • 你为什么要把eventLogin 作为参数?!
  • 因为对我要求很高,我猜是“private void LogIn(ActionEvent event)”
  • 通常一个动作事件也是用回车键触发的,那么为什么还要创建2个事件处理程序呢?

标签: function javafx


【解决方案1】:

有几种方法可以做到这一点。

  1. 您没有理由将 ActionEvent 传递给 Login 方法。如果您删除 ActionEvent 参数,那么您将能够从另一个事件中调用 Login
  2. LoginButton.fire() 将以编程方式单击按钮,然后触发 Login 事件。如果您将 OnKeyPressedListener 添加到您的按钮,并检测到“ENTER”键被点击,您可以通过编程方式点击该按钮,而不必再次调用 Login 方法。

这里有一些链接可帮助您检测按钮上的 Enter 键

Fire Button's onAction with Enter in JavaFX

javafx: How to bind the Enter key to a button and fire off an event when it is clicked?

【讨论】:

    猜你喜欢
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多