How to handle an event from another class in JavaFX?

Hung Do :

I'm trying to have a button in the Launcher class and make a handling function in another class as below. However, the handling function doesn't seem to work. Nothing printed.

I think the function button.setOnAction(anotherclass) is the cause. On some tutorials, they sai the parameter for setOnAction() is where I put the handling function at. So I put anotherclass there.

I know that I can just make a handling function in the same class or just use lambda. However, I'm trying to see if this way works.


public class Launcher extends Application{
    public static Button button;
    AnotherClass anotherclass;
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage myStage) throws Exception {
        button = new Button("Click me");
        button.setOnAction(anotherclass);

        StackPane layout = new StackPane();
        layout.getChildren().add(button);
        Scene scene = new Scene(layout, 300, 250);
        myStage.setScene(scene);
        myStage.show();

    }
}
public class AnotherClass implements EventHandler<ActionEvent>{
    @Override
    public void handle(ActionEvent event) {
        if(event.getSource()== Launcher.button) {   
            System.out.println("print");
        }
    }
}

Can anyone help me make a handling function in a different class as the button's?

Zephyr :

This would be a very strange design to have an entirely different class created for the sole purpose of handling one event, but it can be done. Just not the way you're trying to do it.

If you are set on using this separate AnotherClass to handle it, you just need to pass the class with the new keyword to actually instantiate the class:

button.setOnAction(new AnotherClass());

However, this would be poor design for a couple of reasons:

  1. You are exposing your Button through the public modifier. This is a bad idea and violates the principles of encapsulation.
  2. You would be separating the logic of your application from the UI in a fairly unintuitive manner, making it more challenging to maintain in the future.

My suggestion would be to use an anonymous class and a lambda expression within the setOnAction() method:

button.setOnAction(event -> {
    System.out.println("print");
}

This would have the same result as your current implementation of AnotherClass, but is easier to read, easier to maintain, keeps the logic for your buttons right in the same code, and does not require you to expose your Button publicly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166668&siteId=1