javafx gridpane
In JavaFX, the GridPane
class is a layout container that arranges its child nodes in a grid of rows and columns. You can use it to create complex layouts that consist of multiple elements, such as forms, tables, or dashboards.
Here's an example of how to create and use a GridPane
:
import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class MyJavaFXApp extends Application { @Override public void start(Stage primaryStage) { // Create a GridPane object GridPane gridPane = new GridPane(); // Set the padding and spacing of the GridPane gridPane.setPadding(new Insets(10)); gridPane.setHgap(10); gridPane.setVgap(10); // Create some child nodes and add them to the GridPane Label nameLabel = new Label("Name:"); gridPane.add(nameLabel, 0, 0); Label emailLabel = new Label("Email:"); gridPane.add(emailLabel, 0, 1); Label phoneLabel = new Label("Phone:"); gridPane.add(phoneLabel, 0, 2); Button saveButton = new Button("Save"); gridPane.add(saveButton, 1, 3); // Create some text fields and add them to the GridPane TextField nameField = new TextField(); gridPane.add(nameField, 1, 0); TextField emailField = new TextField(); gridPane.add(emailField, 1, 1); TextField phoneField = new TextField(); gridPane.add(phoneField, 1, 2); // Create a scene and set it on the stage Scene scene = new Scene(gridPane, 300, 200); primaryStage.setScene(scene); // Show the stage primaryStage.show(); } public static void main(String[] args) { launch(args); } }
In this example, we create a GridPane
object and add some child nodes to it, such as Label
objects and TextField
objects. We specify the grid coordinates of each node using the add()
method, which takes the node and the row and column indices as parameters.
We also set the padding and spacing of the GridPane
using the setPadding()
and setHgap()
and setVgap()
methods. The padding specifies the margin around the edges of the GridPane
, while the horizontal and vertical gaps specify the spacing between the columns and rows, respectively.
By default, the GridPane
lays out its child nodes in a way that they occupy their preferred sizes. You can also use the setConstraints()
method to set the size and alignment of each child node, or the setColumnSpan()
and setRowSpan()
methods to merge cells.
The GridPane
is a versatile layout container that can accommodate a variety of UI elements and use cases. It's often used in conjunction with other layout containers, such as HBox
and VBox
, to create more complex layouts.