Radek Červenec
Radek Červenec

Reputation: 115

JavaFX – exclude/include parent and all its children from layout dynamically

Background/Context:

I have a HBox as a parent and many child Nodes (Buttons, TextFields, Labels…). The HBox is a child of other container (BorderPane/VBox/Grid)

My questions:

How do I dynamically remove/exclude the parent (HBox) and all its children from layout?

I am looking for some three-state property on Node (like in Microsoft WPF):

Visible – visible and participate in layout

Collapsed – is not visible and do not participate in layout (applies to its children as well)

Hidden – is not visible but participate in layout

http://msdn.microsoft.com/en-us/library/ms590101.aspx

What options does JavaFX offer?

My solutions so far:

hBox.setManaged(false);    

root.getChildren().remove(hBoxTop);

root.getChildren().add(hBoxTop);

Edited:

Well, I got this working.

Dynamically removing and adding for this specific case can be achieved by:

Remove:

root.setTop(null);

Add:

root.setTop(hBoxTop);

When I did not call setTop(null) on removal, BorderPane still reserved space for HBox (even after removal from its children).

IMHO: it is not very good model as it is parent-container specific. For example if I change, BorderPane to VBox a I had to change these methods as well. For VBox, remove/add on children collection works but I need to remember index so that HBox appears at same place after calling add.

Upvotes: 3

Views: 4091

Answers (2)

Jonathan Mark Mwigo
Jonathan Mark Mwigo

Reputation: 145

Many years later, been facing the same issue but managed to work it out after a good research. So am having a VBox which whose components am updating if a certain condition is filled by the user. setting visible and managed to false completely removes the Nodes from view and setting these back to true shows the Nodes back dynamically.

if (!comboBox.getItems().isEmpty()) {
   vBox.setVisible(true);
   vBox.setManaged(true);
} else {
   vBox.setVisible(false);
   vBox.setManaged(false);
}

The above should work fine.

Upvotes: 1

Flo C
Flo C

Reputation: 421

Using root.setTop(null) is not a good idea because as you say it's specific to BorderPane.

I think the best solution is to use:

root.getChildren().remove(yourPane);

And use layout methods to place your other childrens as you want. But maybe you should not use a BorderPane in the first place with the behaviors you want in your application.

Notice you can also do root.getChildren().clear() to remove all component and add it again to your layout but differently.

Upvotes: 1

Related Questions