JavaFX 的 AnchorPane
是一种布局方式,允许你通过指定锚点来定位子节点。锚点是相对于父节点边缘的位置,你可以使用这些锚点来控制子节点的位置和大小。AnchorPane
非常适合用来创建复杂的布局,其中组件的位置需要相对于其他组件或父容器的边缘进行定位。
以下是 AnchorPane
的一些基本用法:
-
锚点属性:每个子节点都有四个锚点属性:
topAnchor
、bottomAnchor
、leftAnchor
和rightAnchor
。你可以为这些属性设置值,以确定子节点相对于父节点边缘的位置。 -
中心对齐:
AnchorPane
没有内建的居中对齐方式,但可以通过设置左右和上下锚点相等来实现。 -
填充:可以使用
setPadding
方法为AnchorPane
设置内边距。 -
约束优先级:JavaFX 8 引入了约束优先级的概念,允许你为每个锚点设置优先级。
-
自动尺寸调整:
AnchorPane
允许你通过锚点来控制子节点的尺寸,例如,通过将左右锚点设置为相等,子节点的宽度将根据其内容自动调整。
下面是一个 AnchorPane
的使用案例,演示了如何使用锚点来定位组件:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class AnchorPaneDemo extends Application {
@Override
public void start(Stage primaryStage) {
// 创建 AnchorPane 实例
AnchorPane anchorPane = new AnchorPane();
// 创建按钮
Button topButton = new Button("Top");
Button bottomButton = new Button("Bottom");
Button leftButton = new Button("Left");
Button rightButton = new Button("Right");
// 设置按钮的锚点
anchorPane.setTopAnchor(topButton, 10.0);
anchorPane.setLeftAnchor(topButton, 10.0);
anchorPane.setBottomAnchor(bottomButton, 10.0);
anchorPane.setRightAnchor(bottomButton, 10.0);
anchorPane.setLeftAnchor(leftButton, 10.0);
anchorPane.setRightAnchor(leftButton, Double.MAX_VALUE); // 相对于右边缘
anchorPane.setTopAnchor(rightButton, 10.0);
anchorPane.setBottomAnchor(rightButton, 10.0);
anchorPane.setLeftAnchor(rightButton, Double.MAX_VALUE); // 相对于左边缘
// 将按钮添加到 AnchorPane
anchorPane.getChildren().add(topButton);
anchorPane.getChildren().add(bottomButton);
anchorPane.getChildren().add(leftButton);
anchorPane.getChildren().add(rightButton);
// 创建场景并设置 AnchorPane
Scene scene = new Scene(anchorPane, 400, 300);
// 设置舞台并显示
primaryStage.setScene(scene);
primaryStage.setTitle("AnchorPane Demo");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
在这个例子中,我们创建了一个 AnchorPane
并添加了四个按钮。每个按钮都通过锚点属性定位在 AnchorPane
的不同位置。例如,topButton
被定位在顶部和左侧的10像素处,bottomButton
被定位在底部和右侧的10像素处,leftButton
被拉伸以填充左侧和右侧的10像素处,而 rightButton
则被定位在右侧和顶部的10像素处。
运行这个程序,你会看到一个窗口,其中包含四个按钮,它们根据锚点属性被定位在 AnchorPane
的不同位置。通过调整窗口的大小,你可以观察到按钮如何根据锚点属性进行调整。