How to broadcast an event in JavaFX

Given a JavaFX application with multiple presenters and views organized in a hierarchy. How can I broadcast events from the parent presenter to the child presenter / viewer?

My architecture is as follows: I have a MainPresenter that sits on top of the hierarchy

public class MainPresenter { @FXML private TreeView<String> navigation; @FXML private AnchorPane contentView; @Autowired private MainView mainView; @Autowired private DetailView detailView; @FXML public void initialize() { // register a handler for selection of treeview items navigation.getSelectionModel().selectedItemProperty().addListener( new ChangeListener<TreeItem<String>>() { // ... contentView.getChildren().clear(); contentView.getChildren().add(detailView); contentView.fireEvent(new ResourceEvent(ResourceEvent.SELECTED, model)); // ... } ); } } 

There is also a presenter for a detailed presentation of the selected item:

 public class DetailPresenter { @Autowired private DetailView view; @PostConstruct public void postInit() { // is being executed view.getView().addEventHandler(ResourceEvent.SELECTED, (event) -> { // not being invoked }); } } 

What I want to achieve is that whenever the item is selected in the TreeView, the DetailView for this item must be added to the scene graph (it works), and DetailPresenter should be notified when the resource is loaded from the backend service. One solution for this would be to simply auto- DetailPresenter in MainPresenter , which I don't want. I want to have a free connection. As I suggested from the Documentation when processing events , the Event is sent down to all nodes in the scene graph and then returns to the root of the scene. Since the EventHandler in my DetailPresenter not being called, I believe the event is not being dispatched.

My question will be, how to achieve this?

+4
source share
1 answer

MyModel.java :

 public class MyModel { private StringProperty myString = new SimpleStringProperty(); public void setMyString(String myString) { this.myString.set(myString); } public String getMyString() { return myString.get(); } public StringProperty getMyStringProperty() { return myString; } } 

Then create an instance of MyModel as a singleton bean (it looks like you are using Spring). And enter your model where you need it:

 @Bean public MyModel myModel() { return new MyModel(); } 

Then enter it and bind to the property:

 public class MyPresenter { @FXML TextField myTextField; @Autowired MyModel myModel; public void initialize() { myTextField.textProperty().bind(myModel.getMyStringProperty()); } } 

If someone is now updating the myString property, the UI myTextField will also be updated.

You can also register some custom handler for these properties or use twoWayBinding.

Thus, you do not need to use it as a user interface element, but it can also use it as a kind of data pipeline.

0
source

All Articles