Java Reference
In-Depth Information
4
import
javafx.geometry.Pos;
5
import
javafx.scene.Scene;
6
import
javafx.scene.control.Button;
7
import
javafx.scene.control.Label;
8
import
javafx.scene.control.TextField;
9
import
javafx.scene.layout.GridPane;
10
import
javafx.stage.Stage;
11
12
public class
ShowGridPane
extends
Application {
13 @Override
// Override the start method in the Application class
14
public void
start(Stage primaryStage) {
15
// Create a pane and set its properties
16 GridPane pane =
new
GridPane();
17 pane.setAlignment(Pos.CENTER);
18 pane.setPadding(
new
Insets(
11.5
,
12.5
,
13.5
,
14.5
));
19 pane.setHgap(
5.5
);
20 pane.setVgap(
5.5
);
21
22
// Place nodes in the pane
23 pane.add(
new
Label(
"
First Name:
"
),
0
,
0
);
24 pane.add(
new
TextField(),
1
,
0
);
25 pane.add(
new
Label(
"
MI:
"
),
0
,
1
);
26 pane.add(
new
TextField(),
1
,
1
);
27 pane.add(
new
Label(
"
Last Name:
"
),
0
,
2
);
28 pane.add(
new
TextField(),
1
,
2
);
29 Button btAdd =
new
Button(
"
Add Name
"
);
30 pane.add(btAdd,
1
,
3
);
31 GridPane.setHalignment(btAdd, HPos.RIGHT);
32
33
// Create a scene and place it in the stage
34 Scene scene =
new
Scene(pane);
35 primaryStage.setTitle(
"
ShowGridPane
"
);
// Set the stage title
36 primaryStage.setScene(scene);
// Place the scene in the stage
37
create a grid pane
set properties
add label
add text field
add button
align button right
create a scene
primaryStage.show();
// Display the stage
display stage
38 }
39 }
The program creates a
GridPane
(line 16) and sets its properties (line 17-20). The align-
ment is set to the center position (line 17), which causes the nodes to be placed in the center
of the grid pane. If you resize the window, you will see the nodes remains in the center of the
grid pane.
The program adds the label in column
0
and row
0
(line 23). The column and row index
starts from
0
. The
add
method places a node in the specified column and row. Not every cell
in the grid needs to be filled. A button is placed in column 1 and row 3 (line 30), but there
are no nodes placed in column 0 and row 3. To remove a node from a
GridPane
, use
pane.
getChildren().remove(node)
. To remove all nodes, use
pane.getChildren().
removeAll()
.
The program invokes the static
setHalignment
method to align the button right in the
cell (line 31).
Note that the scene size is not set (line 34). In this case, the scene size is automatically
computed according to the sizes of the nodes placed inside the scene.
remove nodes
14.10.3
BorderPane
A
BorderPane
can place nodes in five regions: top, bottom, left, right, and center, using
the
setTop(node)
,
setBottom(node)
,
setLeft(node)
,
setRight(node)
, and
setCenter(node)
methods. The class diagram for
GridPane
is shown in FigureĀ 14.20.
Search WWH ::
Custom Search