【发布时间】:2020-03-15 02:55:23
【问题描述】:
我想知道如何将事件从孩子发送给父母。 我写了这段代码,如果选择目录,我可以在 ImageView 上看到目录中的第一张图片。
按下按钮并选择目录后,我想将路径发送到 ParentController。 但是,现在我无法发送,因为在创建窗口时调用了 getCurrentPath()。
父控制器
@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;
}
}
【问题讨论】:
-
从理论上讲,您可以通过将侦听器传递给得到通知的方法来执行类似的操作(或者简单地使用侦听器来传递为此目的传递的
ImageView的image属性)。但是,您的类之间的职责分配不是最理想的,并且命名也不完美;OpenDirectoryButton,与顾名思义相反,不是按钮,而是能够创建按钮的类。在这种情况下,将static用于OpenDirectoryButton.path几乎可以肯定是错误的...