Search code examples
javajavafxfxml

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


I am trying to minimize the amount of code needed to click a button, but because I have a picture on each button, if the user clicks the image then it also needs to go to the appropriate page. Is there a way in which I can call the same method from the non-image button (which is an ActionEvent and the image has a parameter of MouseEvent)

I tried fixing the error using the IDE's option to create a method for this, but it didn't seem to do anything.

    @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);
        }
    }

Nothing wrong with the output, I'm just trying to minimize on the code, as I have 6 buttons, all with this same problem


Solution

  • All JavaFX events are descendant from javafx.event.Event; this is where the getSource() method comes from1. As the source of the event appears to be the only thing you need from the parameter, you could simply have one method whose single parameter type is Event. Then configure onAction and onMouseClicked to use that method in your FXML file.

    Another option is to have a third method that handles showing your "new or edit player" dialog. Then you'd simply have your event-handler methods call that third method.


    1. The getSource() method actually comes from java.util.EventObject, which Event extends. But as we're using JavaFX, Event should be considered the top of the hierarchy.