从另一个类调用`setOnAction` [英] Calling `setOnAction` from another class

查看:229
本文介绍了从另一个类调用`setOnAction`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按代码添加JavaFX按钮时,如何从另一个类调用该按钮的 .setOnAction 方法。

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

但是如果我想为此使用控制器,怎么能'链接' actionEvent到另一个类中的方法。


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


推荐答案

什么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

或者:

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

这篇关于从另一个类调用`setOnAction`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆