AnchorPane
AnchorPane is a layout container in JavaFX that lets you position elements by attaching them to the edges of the pane: top, bottom, left, and right.
This is useful when you want a control to stay in a fixed position even if the window is resized.
Example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class AnchorPaneExample extends Application {
@Override
public void start(Stage stage) {
Button topLeftButton = new Button("Top Left");
Button bottomRightButton = new Button("Bottom Right");
AnchorPane root = new AnchorPane();
root.getChildren().addAll(topLeftButton, bottomRightButton);
// Attach the first button 10px from the top and left
AnchorPane.setTopAnchor(topLeftButton, 10.0);
AnchorPane.setLeftAnchor(topLeftButton, 10.0);
// Attach the second button 10px from the bottom and right
AnchorPane.setBottomAnchor(bottomRightButton, 10.0);
AnchorPane.setRightAnchor(bottomRightButton, 10.0);
Scene scene = new Scene(root, 400, 300);
stage.setTitle("AnchorPane Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
What happens:
topLeftButtonalways stays 10 pixels from the top-left corner.bottomRightButtonalways stays 10 pixels from the bottom-right corner.- If the window becomes larger or smaller, the buttons keep those distances.
You can also anchor an element on both left and right sides so it stretches:
TextField textField = new TextField();
root.getChildren().add(textField);
AnchorPane.setTopAnchor(textField, 20.0);
AnchorPane.setLeftAnchor(textField, 20.0);
AnchorPane.setRightAnchor(textField, 20.0);
Now the TextField will grow and shrink horizontally when the window is resized.
FXML version:
<AnchorPane prefWidth="400" prefHeight="300"
xmlns:fx="http://javafx.com/fxml">
<children>
<Button text="Top Left"
AnchorPane.topAnchor="10.0"
AnchorPane.leftAnchor="10.0"/>
<Button text="Bottom Right"
AnchorPane.bottomAnchor="10.0"
AnchorPane.rightAnchor="10.0"/>
</children>
</AnchorPane>
Common anchor methods:
AnchorPane.setTopAnchor(node, 10.0);
AnchorPane.setBottomAnchor(node, 10.0);
AnchorPane.setLeftAnchor(node, 10.0);
AnchorPane.setRightAnchor(node, 10.0);
A node can have:
- only top + left
- only bottom + right
- left + right (stretch horizontally)
- top + bottom (stretch vertically)
- all four (stretch in both directions)
For example, to make a ListView fill almost the whole window:
AnchorPane.setTopAnchor(listView, 10.0);
AnchorPane.setBottomAnchor(listView, 10.0);
AnchorPane.setLeftAnchor(listView, 10.0);
AnchorPane.setRightAnchor(listView, 10.0);