Mastering JavaFX 10
上QQ阅读APP看书,第一时间看更新

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: