javafx布局类AnchorPane

AnchorPane继承与Pane,基本属性与方法与Pane相同。

Anchor有锚的意思,AnchorPane即锚布局,可以设置子节点位置。

public class TestAnchorPane  extends Application{
	public static void main(String[] args) {
		launch();
	}
	public void start(Stage primaryStage) throws Exception {
		AnchorPane anchorPane=new AnchorPane();
		anchorPane.setPrefSize(300, 300);
		anchorPane.setStyle("-fx-background-color:#1E90FF;");
		Scene scene=new Scene(anchorPane);
		primaryStage.setScene(scene);
		primaryStage.setTitle("TestAnchorPane");
		primaryStage.show();
	}
}

在这里插入图片描述

添加节点

添加节点方法与Pane相同,默认添加于(0,0)处,多个将重叠在一起。

	Button button=new Button ("button");
	anchorPane.getChildren().add(button);

在这里插入图片描述

子节点设置

和Pane不同的是AnchorPane可以设置子节点的相对位置,并且能改变子节点大小

距上边界50个像素

anchorPane.setTopAnchor(button, 50.0);

在这里插入图片描述

距右边界10个像素

anchorPane.setRightAnchor(button, 10.0);

在这里插入图片描述

距下边界20个像素,button被拉长。

anchorPane.setBottomAnchor(button,20.0);

在这里插入图片描述

距左边界10个像素,button被拉宽。

	anchorPane.setLeftAnchor(button, 10.0);

在这里插入图片描述

与此同时button被AnchorPane托管,鼠标拖动改变窗口大小,button随之改变,但与边界距离保持不变,
且button.setLayoutX方法将失效。
在这里插入图片描述
AnchorPane继承自Pane,同样可以设置监听器。

猜你喜欢

转载自blog.csdn.net/qq_39464369/article/details/88993178
今日推荐