简体   繁体   中英

Calling `setOnAction` from another class

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

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
    }
}

What about:

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

Then the event handler is attach to the button but its triggering call a method from your controller


Or:

public class SomeClass{
    SomeClassController ctrl = new SomeClassController();
    private SomeClassController controller;
    Button continueButton = new Button("Continue");
    continueButton.setOnAction(ctrl.getHandler());
}

public class SomeClassController{

   private EventHandler<ActionEvent> EH;

   public SomeClassController(){
       EH = new EventHandler<ActionEvent>() {
           @Override
           public void handle(ActionEvent event) {
              someMethod();
           }
       });
}

public EventHandler<ActionEvent> getHandler(){
return EH;
}

public void someMethod(){
//DO SOMETHING
}
}

I didn't test the code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM