Skip to content
Advertisement

Dynamically adding nodes in JavaFX

I’m trying to build a chat application that implements Group chat in JavaFX. I want to make a Scroll Pane inside of a Border pane that will contain all Groups in which the User is member of. The Groups icons (ImageViews) need to be added dynamically(cannot be done in Scene Builder) to the Scroll Pane(inside of a HBox) as the User is joining them.

enter image description here

Currently I’m using a SceneController class that is responsible for all Stage and Scene changes.

JavaScript

I already created an FXML file(using scene builder) which contains Border Pane and a Scroll Pane as top child.

JavaScript

My plan is to populate all Groups(on initialization) to the Scroll Pane in the Page controller.

JavaScript

I already tried to create a Scene with the updated Border Pane, but I get an error “borderPane is already set as root of another scene”. I also tried to directly change the root of the already existing scene, but I get a NullPointerException in that case.

Could you please advise which is the best way to add Nodes dynamically to a Scroll Pane. I will be grateful for comments about the project structure too.

Advertisement

Answer

Could you please advise which is the best way to add Nodes dynamically to a Scroll Pane.

You need a reference to the content of the ScrollPane (the HBox in this case), and a method to add things to it:

JavaScript

When you load the FXML, keep a reference to the controller:

JavaScript

And then you can add things to the scroll pane with

JavaScript

As mentioned in another answer, a ListView may be a better approach to this.

You should also probably consider a MVC approach (see, for example, Applying MVC With JavaFx), where the model uses an ObservableList<...> to store the list of groups. The controller can observe that list and modify the scroll pane content when it changes. Then all you have to do is add something to the list via the model.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement