如何将事件从子类发送到父类

我想知道有关从孩子向父母发送事件的信息。 我编写了这段代码,如果选择目录,则可以在ImageView的目录中看到第一张图片。

按下按钮并选择目录后,我想将路径发送到ParentController。 但是,现在我无法发送,因为在创建窗口时会调用getcurrentPath()。

ParentController

@FXML private Button openDirButton;
@FXML private ImageView mainImageView;

@FXML
public void initialize(URL location,ResourceBundle resources) {

    // Choosing Directory Button
    opendirectoryButton ODB = new opendirectoryButton();
    ODB.getDirSetImageSetListView(openDirButton,mainImageView);
    String currentPath = ODB.getcurrentPath();
    System.out.println(currentPath); // null

ChildController

public class opendirectoryButton {

    public static String path;
    public Button getDirSetImageSetListView(Button button,ImageView imageView) {
        button.setOnaction(actionEvent -> {
            // This is a class I made
            DirectoryChoose DC = new DirectoryChoose();
            // Get a Directory Path
            path = DC.getPath();
            // Get a list of path of images
            imageList = DC.getimagelist(path);
            image = new Image("file:///" + path + File.separator + imageList.get(0));
            imageView.setImage(image);
        });
        return button;
    }
    public String getcurrentPath() {
        return path;
    }
}
myidgy 回答:如何将事件从子类发送到父类

要与事件一起使用,有几种方法。

1)https://github.com/AlmasB/FXEventBus。您可以将其集成到项目中,然后可以用于处理事件。

2)您可以像静态字段一样声明您的类,并将其发送给您的孩子,然后从孩子类中使用您的字段。

ParentController

在班级领域

public static ParentConrtroller instance; // Not good declare field in public

    ***
    public void inititalize(URL location,ResourceBundle resources){
     instance = this;
}

子控制器

ParentController.instance //and every public method of Parent is available for your 
,

将消费者传递到getDirSetIgmageSetListView

ParentController

ODB.getDirSetImageSetListView(openDirButton,mainImageView,path->{
    System.out.println(path);
});

ChildController

public Button getDirSetImageSetListView(Button button,ImageView imageView,Consumer<String> pathConsumer) {
    button.setOnAction(actionEvent -> {
        // This is a class I made
        DirectoryChoose DC = new DirectoryChoose();
        // Get a Directory Path
        path = DC.getPath();
        // Get a list of path of images
        imageList = DC.getImageList(path);
        image = new Image("file:///" + path + File.separator + imageList.get(0));
        imageView.setImage(image);
        imageConsumer.accept(path); //execute consumer with your path variable
    });
    return button;
}
本文链接:https://www.f2er.com/2644972.html

大家都在问