In this tutorial you will learn the GridPane component via simple examples.
What is a GridPane?
GridPane is a JavaFX component that lays out its children within a flexible grid of rows and columns.
If a border and/or padding is set, then its content will be laid out within those insets. A child may be placed anywhere within the grid and may span multiple rows/columns.
Children may freely overlap within rows/columns and their stacking order will be defined by the order of the gridpane’s children list (0th node in back, last node in front).
Example 1: NumberPad with GridPane
We will use GridPane and Buttons to create a numberpad, not unlike the one you see in calculators.
Here is the demo screenshot:
Step 1: Create Project
Start by creating a JavaFX program in your preferred editor or IDE.
Step 2: Write Code
Hereis the full code:
MyGridPane.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
public class MyGridPane extends Application
{
@Override
public void start(Stage primaryStage)
{
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 180, 250);
String[] keys =
{
"1", "2", "3",
"4", "5", "6",
"7", "8", "9",
"*", "0", "#"
};
GridPane numPad = new GridPane();
for (int i = 0; i < 12; i++)
{
Button button = new Button(keys[i]);
button.getStyleClass().add("num-button");
numPad.add(button, i % 3, (int) Math.ceil(i / 3));
}
Button call = new Button("Call");
call.setId("call-button");
call.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
numPad.add(call, 0, 4);
GridPane.setColumnSpan(call, 3);
GridPane.setHgrow(call, Priority.ALWAYS);
root.setCenter(numPad);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
Run
Lastly run the project.If you are using an IDE just click the run button in that IDE.
If you are using terminal then cd
or navigate to that project using the cd
command then run using the javac
command as follows:
cd "d:\Projects\Java\JavaFX\YourJavaExample\" && javac YourJavaExample.java && java YourJavaExample
That will run the project.
Download
Just copy the source code above into your project.