Reputation: 11
I want to know about sending event from child to parent. I wrote this code, and if choosing a directory, I can see a first picture in a directory on ImageView.
After pushing a button and selecting a directory, I want to send path to ParentController. But, now I cannot send because getCurrentPath() is called when creating a window.
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;
}
}
Upvotes: 0
Views: 522
Reputation: 2560
Pass a consumer to getDirSetIgmageSetListView
ODB.getDirSetImageSetListView(openDirButton, mainImageView, path->{
System.out.println(path);
});
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;
}
Upvotes: 0
Reputation: 470
For using with Events there is several ways.
1)https://github.com/AlmasB/FXEventBus. You could integrate it into your project then might to use to manipulate with events.
2) You could declare your class like static field and send to your child and from child class you will use your fields Not good example to use.
ParentController
in field of class
public static ParentConrtroller instance; // Not good declare field in public
***
public void inititalize(URL location, ResourceBundle resources){
instance = this;
}
Child Controller
ParentController.instance //and every public method of Parent is available for your
Upvotes: 1