AnchorPane
a is a layout that allows placing the content at a specific distance from it's sides.
There are 4 methods for setting and 4 methods for getting the distances in AnchorPane
. The first parameter of these methods is the child Node
. The second parameter of the setters is the Double
value to use. This value can be null
indicating no constraint for the given side.
setter method | getter method |
---|---|
setBottomAnchor | getBottomAnchor |
setLeftAnchor | getLeftAnchor |
setRightAnchor | getRightAnchor |
setTopAnchor | getTopAnchor |
In the following example places nodes at specified distances from the sides.
The center
region is also resized to keep the specified distances from the sides. Observe the behaviour when the window is resized.
public static void setBackgroundColor(Region region, Color color) {
// change to 50% opacity
color = color.deriveColor(0, 1, 1, 0.5);
region.setBackground(new Background(new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY)));
}
@Override
public void start(Stage primaryStage) {
Region right = new Region();
Region top = new Region();
Region left = new Region();
Region bottom = new Region();
Region center = new Region();
right.setPrefSize(50, 150);
top.setPrefSize(150, 50);
left.setPrefSize(50, 150);
bottom.setPrefSize(150, 50);
// fill with different half-transparent colors
setBackgroundColor(right, Color.RED);
setBackgroundColor(left, Color.LIME);
setBackgroundColor(top, Color.BLUE);
setBackgroundColor(bottom, Color.YELLOW);
setBackgroundColor(center, Color.BLACK);
// set distances to sides
AnchorPane.setBottomAnchor(bottom, 50d);
AnchorPane.setTopAnchor(top, 50d);
AnchorPane.setLeftAnchor(left, 50d);
AnchorPane.setRightAnchor(right, 50d);
AnchorPane.setBottomAnchor(center, 50d);
AnchorPane.setTopAnchor(center, 50d);
AnchorPane.setLeftAnchor(center, 50d);
AnchorPane.setRightAnchor(center, 50d);
// create AnchorPane with specified children
AnchorPane anchorPane = new AnchorPane(left, top, right, bottom, center);
Scene scene = new Scene(anchorPane, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}