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

标签 java javafx fxml

我想了解如何将事件从 child 发送到 parent 。 我写了这段代码,如果选择一个目录,我可以在 ImageView 上看到目录中的第一张图片。

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

父 Controller

@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

子 Controller

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

最佳答案

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

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

2)您可以像静态字段一样声明您的类并将其发送给您的 child ,并且从子类中您将使用您的字段这不是很好的例子。

父 Controller

在类领域

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

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

子 Controller

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

关于java - 如何将事件从子类发送到父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60689326/

相关文章:

java - 如何在javafx中将父AnchorPane与HBox匹配

java - 使用maven将照片添加到javafx中的按钮时出现问题

java FXML 生成的代码

Java PriorityQueue Comparator - 如何/何时排序?

java - 将字符串解析为日期 - Java

java - JPA中@javax.persistence.Lob注解有什么意义?

javafx - 在 fxml 中绑定(bind)两个以上的属性

java - 将两个数组合并为一个交替元素?

javafx - 如何在javafx中使子级自动调整大小(子级是 Pane ,父级是VBox)

Java 在尝试运行 fxml 时找不到或加载主类