Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When adding a JavaFX button by code, how can I call the .setOnAction method of the button from another class.

For instance, if I was to handle the button press within the same class:

public class SomeClass{
    Button continueButton = new Button("Continue");
    continueButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            someMethod();
        }
    });
}

However if I wish to utilise a controller for this, how can 'link' the actionEvent to a method within the other class.
eg:

public class SomeClass{
    private SomeClassController controller;
    Button continueButton = new Button("Continue");
    continueButton.setOnAction(
        //Call continuePressed() on controller
    );
}

public class SomeClassController{
    public void continuePressed(){
        someMethod();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
214 views
Welcome To Ask or Share your Answers For Others

1 Answer

Barbe Rouge is right. A somewhat simpler solution using Java 8 syntax would be:

public class SomeClass {

    private final SomeClassController controller = new SomeClassController();

    public SomeClass() {
        final Button button = new Button("Click me!");
        button.setOnAction(controller::handle);
    }

}

public class SomeClassController {
    public void handle(ActionEvent event) {
        // Do something
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...