如何在另一个方法中使用相同 class 中的方法,这需要不同的参数

How to use a method in the same class in another method, which requires a different parameter

我试图尽量减少单击按钮所需的代码量,但因为我在每个按钮上都有一张图片,所以如果用户单击该图片,则它也需要转到相应的页面。有没有一种方法可以让我从非图像按钮(这是一个 ActionEvent 并且图像具有 MouseEvent 的参数)调用相同的方法

我尝试使用 IDE 的选项为此创建一个方法来修复错误,但它似乎没有做任何事情。

    @FXML
    private void clickedNewPlayer(ActionEvent event) {
        try {
            ((Node) event.getSource()).getScene().getWindow().hide();
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("New or Edit Player Screen.fxml"));
            Parent root1 = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.setScene(new Scene(root1));
            stage.show();
        } catch (IOException e) {
            System.out.println("Error in opening window" + e);
        }
    }

    @FXML
    private void clickedNewPlayerImage(MouseEvent event) {
        try {
            ((Node) event.getSource()).getScene().getWindow().hide();
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("New or Edit Player Screen.fxml"));
            Parent root1 = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.setScene(new Scene(root1));
            stage.show();
        } catch (IOException e) {
            System.out.println("Error in opening window" + e);
        }
    }

输出没有问题,我只是想尽量减少代码,因为我有 6 个按钮,都有同样的问题

所有 JavaFX 事件都是 javafx.event.Event 的后代;这就是 getSource() 方法来自 1 的地方。由于事件源似乎是您唯一需要的参数,因此您可以简单地使用一种方法,其单个参数类型为 Event。然后配置 onActiononMouseClicked 以在您的 FXML 文件中使用该方法。

另一种选择是使用第三种方法来处理 "new or edit player" 对话框的显示。然后你只需让你的事件处理程序方法调用第三个方法。


1. getSource() 方法实际上来自 java.util.EventObjectEvent 对其进行了扩展。但是因为我们使用的是 JavaFX,所以 Event 应该被认为是层次结构的顶部。