Calling `setOnAction` from another class

青春壹個敷衍的年華 提交于 2019-12-25 06:07:39

问题


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

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/32776970/calling-setonaction-from-another-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!