Home » Java » How to get JavaFX HBoxes to move items to the next line?

How to get JavaFX HBoxes to move items to the next line?

Posted by: admin December 28, 2021 Leave a comment

Questions:

I’m trying to show a HBox which contains a list of checkboxes. Example:

HBox container = new HBox();
for (Weekday day: Weekday.values() )
{
   container.getChildren().add( new CheckBox( day.getName() ) ); 
}

However this shows the days all on one line, as:

Sunday Monday Tuesday Wednesday Thursday Friday Saturday

The window is not big enough to show them all on one line, and so I get a horizontal scrollbar. What I need is to show the days on two lines, e.g:

Sunday Monday Tuesday Wednesday
Thursday Friday Saturday

I’ve tried container.setPrefWidth() but it just causes it to show Su.., Mo.. to truncate the text rather than moving them to the next line.

Answers:

You should try using FlowPane. I tried it and got the result you’ve been seeking for.

The HBox layout pane provides an easy way for arranging a series of nodes in a single row

The nodes within a FlowPane layout pane are laid out consecutively and wrap at the boundary set for the pane. Nodes can flow vertically (in columns) or horizontally (in rows). A vertical flow pane wraps at the height boundary for the pane. A horizontal flow pane wraps at the width boundary for the pane.

source: http://docs.oracle.com/javafx/2/layout/builtin_layouts.htm#CHDGHCDG
(its a useful read)