iCodeSometime
iCodeSometime

Reputation: 1662

How to limit the number of columns in a javafx vertical flowpane

I am mainly using scene builder to create the ui for my javafx application. I am currently using a vertical FlowPane to get it arranged the way I would like, however instead of continuing downward the way I would like it to, it continues off the right side of the window.

Application image

I have drawn red outlines to demonstrate where I would like to have the other boxes positioned. Is FlowPane the appropriate container to use for this? And if so, how can I get this to work?

Upvotes: 1

Views: 2791

Answers (1)

eckig
eckig

Reputation: 11154

Look at this sample Application:

private static final Random rand = new Random();
private static final int max = 200;

@Override
public void start(Stage primaryStage) {
    try {
        FlowPane root = new FlowPane(Orientation.VERTICAL);
        root.setPrefWrapLength(5000);
        root.setPadding(new Insets(10));
        root.setHgap(10);
        root.setVgap(10);

        for (int i = 0; i < 200; i++) {
            Rectangle rectangle = new Rectangle(50, 50);
            rectangle.setFill(Color.rgb((int) (rand.nextDouble() * max),
                    (int) (rand.nextDouble() * max),
                    (int) (rand.nextDouble() * max)));
            root.getChildren().add(rectangle);
        }

        Scene scene = new Scene(new ScrollPane(root), 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The line root.setPrefWrapLength(5000); is the important one, as FlowPane.setPrefWrapLength() determines how large (in pixels) the FlowPane will grow.

As your FlowPane is VERTICAL, root.setPrefWrapLength(5000); determines that each column grows at maximum 5000 downwards. After that a new column is created.

If you want to limit the number of columns, or in other words: The maximum width of your FlowPane you should switch from VERTICAL to HORIZONTAL as FlowPane.setPrefWrapLength() will then limit the width of your pane.

Upvotes: 3

Related Questions