JavaFX布局-StackPane
- 常用属性
- alignment
- padding
- 实现方式
- Java实现
- fxml实现
- 所有子节点堆叠在一起,通常最后一个添加的子节点会显示在最上面
常用属性
alignment
对齐方式
stackPane.setAlignment(Pos.CENTER_RIGHT);
public enum Pos {
/**
* Represents positioning on the top vertically and on the left horizontally.
*/
TOP_LEFT(TOP, LEFT),
/**
* Represents positioning on the top vertically and on the center horizontally.
*/
TOP_CENTER(TOP, HPos.CENTER),
/**
* Represents positioning on the top vertically and on the right horizontally.
*/
TOP_RIGHT(TOP, RIGHT),
/**
* Represents positioning on the center vertically and on the left horizontally.
*/
CENTER_LEFT(VPos.CENTER, LEFT),
/**
* Represents positioning on the center both vertically and horizontally.
*/
CENTER(VPos.CENTER, HPos.CENTER),
/**
* Represents positioning on the center vertically and on the right horizontally.
*/
CENTER_RIGHT(VPos.CENTER, RIGHT),
/**
* Represents positioning on the bottom vertically and on the left horizontally.
*/
BOTTOM_LEFT(BOTTOM, LEFT),
/**
* Represents positioning on the bottom vertically and on the center horizontally.
*/
BOTTOM_CENTER(BOTTOM, HPos.CENTER),
/**
* Represents positioning on the bottom vertically and on the right horizontally.
*/
BOTTOM_RIGHT(BOTTOM, RIGHT),
/**
* Represents positioning on the baseline vertically and on the left horizontally.
*/
BASELINE_LEFT(BASELINE, LEFT),
/**
* Represents positioning on the baseline vertically and on the center horizontally.
*/
BASELINE_CENTER(BASELINE, HPos.CENTER),
/**
* Represents positioning on the baseline vertically and on the right horizontally.
*/
BASELINE_RIGHT(BASELINE, RIGHT);
}
padding
容器边缘与其子节点之间的距离
stackPane.setPadding(new Insets(5, 10, 5, 10));
实现方式
Java实现
public static StackPane demo1() {
// 创建StackPane
StackPane stackPane = new StackPane();
// 对齐方式
stackPane.setAlignment(Pos.CENTER);
// 内边距
stackPane.setPadding(new Insets(10, 10, 10, 10));
// 圆形
Circle circle = new Circle(100, Color.RED);
// 矩形
Rectangle rectangle = new Rectangle(120, 100, Color.BLUE);
// 按钮
Button button = new Button("Button 1");
// 添加子节点
stackPane.getChildren().addAll(circle, rectangle, button);
return stackPane;
}
fxml实现
<StackPane alignment="CENTER" prefHeight="400" prefWidth="600" xmlns="http://javafx.com/javafx/17.0.2-ea"
xmlns:fx="http://javafx.com/fxml/1">
<padding>
<Insets bottom="10" left="10" right="10" top="10"/>
</padding>
<Circle fill="red" radius="100"/>
<Rectangle fill="blue" height="100" width="120"/>
<Button text="button 1"/>
</StackPane>