我想了解如何将事件从 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/