📜  JavaFX gridpane(1)

📅  最后修改于: 2023-12-03 14:42:22.141000             🧑  作者: Mango

JavaFX GridPane

GridPane is a layout manager in JavaFX that arranges its child nodes in a grid of rows and columns. It is very useful for creating user interfaces with a structured layout.

Creating a GridPane

To create a GridPane, first import the necessary classes:

import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
import javafx.scene.layout.ColumnConstraints;

Then create a new instance of the GridPane class:

GridPane gridPane = new GridPane();
Adding Nodes to a GridPane

Adding nodes to a GridPane is done using the add() method. This method takes the node to add and the row and column indexes to add it to:

gridPane.add(node, colIndex, rowIndex);

You can also specify additional parameters to dictate how the node should be positioned and sized within the cell:

gridPane.add(node, colIndex, rowIndex, colSpan, rowSpan);
GridPane.setConstraints(node, colIndex, rowIndex, colSpan, rowSpan, hAlign, vAlign, hGrow, vGrow, hIndent, vIndent);

The first version of add() specifies the number of columns and rows the node should span, whereas the second version allows you to specify alignment, growth, and indentation values.

Setting Constraints on Rows and Columns

You can set constraints on rows and columns by creating instances of the RowConstraints and ColumnConstraints classes and assigning them to the GridPane:

RowConstraints rowConstraints = new RowConstraints();
rowConstraints.setPercentHeight(50);
gridPane.getRowConstraints().add(rowConstraints);

ColumnConstraints colConstraints = new ColumnConstraints();
colConstraints.setPercentWidth(50);
gridPane.getColumnConstraints().add(colConstraints);

The code above creates a row that takes up 50% of the height of the GridPane and a column that takes up 50% of the width.

Adding Styling to a GridPane

You can add styling to a GridPane using CSS. To apply CSS styling to a GridPane, you can either apply a stylesheet to the scene or by adding inline CSS:

gridPane.setStyle("-fx-background-color: #FFFFFF;");
gridPane.getStylesheets().add("style.css");

The setStyle() method takes CSS styling as a string argument, whereas the getStylesheets() method allows you to add a CSS stylesheet to the GridPane.

Conclusion

GridPane is a powerful layout manager in JavaFX that can help you create user interfaces with a structured layout. It allows you to easily add nodes to a grid of rows and columns, set constraints, and add styling.