Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering JavaFX 10

You're reading from  Mastering JavaFX 10

Product type Book
Published in May 2018
Publisher Packt
ISBN-13 9781788293822
Pages 268 pages
Edition 1st Edition
Languages
Author (1):
Sergey Grinev Sergey Grinev
Profile icon Sergey Grinev
Toc

Table of Contents (15) Chapters close

Preface 1. Stages, Scenes, and Layout 2. Building Blocks – Shapes, Text, and Controls 3. Connecting Pieces – Binding 4. FXML 5. Animation 6. Styling Applications with CSS 7. Building a Dynamic UI 8. Effects 9. Media and WebView 10. Advanced Controls and Charts 11. Packaging with Java9 Jigsaw 12. 3D at a Glance 13. What's Next? 14. Other Books You May Enjoy

Organizing the Scene content with Layout Managers

In this section, we will review various Layout Managers that control how your nodes are organized on a Scene.

Layout Managers don't have much UI by themselves; usually, only the background and borders are visible and customizable. Their main role is to manage their children nodes.

Free layout

The following managers don't relocate or resize your nodes at all: Pane, Region, and Group. You set coordinates for each of your nodes manually. You can use these layout managers when you want to set absolute positions for each element, or when you want to write your own layout logic.

Let's review the difference between these free layout managers.

The most basic layout manager – Group

Group is a very lightweight layout manager. It doesn't support a lot of customizing options (for example, background color) and doesn't have any size control—Group's size is a combination of child sizes, and anything too large will be trimmed.

So, unless you need to have a huge amount of components and care a lot about performance, consider using another manager.

Region and Pane layout managers

Region and Pane support the whole range of styles and effects. They are used as a basis for almost all JavaFX UI components.

The only difference between them is an access level to their children's list.

Pane gives the public access to the getChildren() method. So, it's used as an ancestor to layout managers and controls which API allows the manipulating of children.

Region, on the other hand, doesn't allow changing its children list. getChildren() is a private method, so the only way to access them is Region.getChildrenUnmodifiable(), which doesn't allow you to change the list. This approach is used when a component is not meant to have new children. For example, all Controls and Charts extend Region.

Behavioral layout

For these layout managers, you choose the behavior for layouting of your nodes, and they will do the following tasks for you:

  • Calculate child nodes' sizes
  • Initial positioning of the child nodes
  • Reposition nodes if they change their sizes or the layout manager changes its size

The first manager to look at is HBox. It arranges its children in simple rows:

HBox root = new HBox(5);
root.getChildren().addAll(
new Rectangle(50, 50, Color.GREEN),
new Rectangle(75, 75, Color.BLUE),
new Rectangle(90, 90, Color.RED));

The corresponding VBox does the same for columns.

StackPane positions nodes in its center.

As nodes will overlap here, note that you can control their Z-order using the following APIs:

  • Node.toBack() will push it further from the user
  • Note.toFront() will bring it to the top position

Take a look at the following example code:

 Pane root = new StackPane();
Rectangle red;
root.getChildren().addAll(
new Rectangle(50, 50, Color.GREEN), // stays behind blue and red
new Rectangle(75, 75, Color.BLUE),
red = new Rectangle(90, 90, Color.RED));

red.toBack();

This is the image that it produces:

Positional layout

This group of managers allows you to choose a more precise location for each component, and they do their best to keep the node there. Each manager provides a distinct way to select where you want to have your component. Let's go through examples and screenshots depicting that.

TilePane and FlowPane

TilePane places nodes in the grid of the same-sized tiles. You can set preferable column and row counts, but TilePane will rearrange them as space allows.

In the following example, you can see different rectangles being located in the same-sized tiles:

Refer to the following code:

// chapter1/layoutmanagers/TilePaneDemo.java
public class TilePaneDemo extends Application {

@Override
public void start(Stage primaryStage) {
TilePane root = new TilePane(5,5);
root.setPrefColumns(4);
root.setPrefRows(4);
// compare to
// FlowPane root = new FlowPane(5, 5);

for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
double size = 5 + 30 * Math.random();
Rectangle rect = new Rectangle(size, size,
(i+j)%2 == 0 ? Color.RED : Color.BLUE);
root.getChildren().add(rect);
}
}

Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle(root.getClass().getSimpleName());
primaryStage.setScene(scene);
primaryStage.show();
}
}

If you don't need tiles to have the same size, you can use FlowPane instead. It tries to squeeze as many elements in the line as their sizes allow. The corresponding FlowPaneDemo.java code sample differs from the last one only by the layout manager name, and produces the following layout:

BorderPane layout manager

BorderPane suggests several positions to align each subnode: top, bottom, left, right, or center:

Refer to the following code:

BorderPane root = new BorderPane();
root.setRight(new Text("Right "));
root.setCenter(new Text("Center"));
root.setBottom(new Text(" Bottom"));
root.setLeft(new Text(" Left"));

Text top = new Text("Top");
root.setTop(top);

BorderPane.setAlignment(top, Pos.CENTER);

Note the last line, where the static method is used to adjust top-element horizontal alignment. This is a JavaFX-specific approach to set Pane constraints.

AnchorPane layout manager

This manager allows you to anchor any child Node to its sides to keep them in place during resizing:

Refer to the following code:

Rectangle rect = new Rectangle(50, 50, Color.BLUE);

Pane root = new AnchorPane(rect);
AnchorPane.setRightAnchor(rect, 20.);
AnchorPane.setBottomAnchor(rect, 20.);

GridPane layout manager

GridPane is most complex layout manager; it allows users to sets rows and columns where child Nodes can be placed.

You can control a lot of constraints through the API: grow strategy, the relative and absolute sizes of columns and rows, resize policy, and so on. I won't go through all of them to avoid repeating JavaDoc, but will show only a short sample—let's make a small chessboard pattern using GridPane:

GridPane root = new GridPane();
for (int i = 0; i < 5; i++) {
root.getColumnConstraints().add(new ColumnConstraints(50));
root.getRowConstraints().add(new RowConstraints(50));
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if ((i+j)%2 == 0)
root.add(new Rectangle(30, 30, Color.BLUE), i, j);
}
}

We get the following output:

You have been reading a chapter from
Mastering JavaFX 10
Published in: May 2018 Publisher: Packt ISBN-13: 9781788293822
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}