从另一个类调用`setOnAction`

时间:2015-09-25 07:28:06

标签: java javafx

按代码添加JavaFX按钮时,如何从其他类调用按钮的.setOnAction方法。

例如,如果我要在同一个班级内按下按钮:

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

但是,如果我希望为此使用控制器,如何将actionEvent“链接”到另一个类中的方法。
例如:

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

public class SomeClassController{
    public void continuePressed(){
        someMethod();
    }
}

2 个答案:

答案 0 :(得分:1)

Barbe Rouge是对的。使用Java 8语法的一个稍微简单的解决方案是:

StateT

答案 1 :(得分:0)

怎么样:

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

然后事件处理程序附加到按钮,但它的触发器从控制器调用方法

或者:

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

我没有测试代码......