Javafx 简明教程

JavaFX - Stackpane Layout

StackPane Layout in JavaFX

StackPane 布局充当容器,将所有子节点排列在彼此顶部,就像栈一样。首先添加的节点置于栈的底部,后续节点置于其顶部。在下面的图片中,StackPane 布局通过将三个矩形框按顺序堆叠来进行说明。它展示了这种类型布局的创意潜力有多大。

sample stackpane

在程序包 javafx.scene.layout 中名为 StackPane 的类表示 StackPane。此类包含一个名为 alignment 的属性。该属性表示 stack pane 内节点的对齐方式。

StackPane 类的构造函数列表如下 −

  1. StackPane() − 它是构造具有居中对齐方式的空 StackPane 布局的默认构造函数。

  2. StackPane(Node childNodes) − 它是使用指定子节点和居中对齐方式创建 StackPane 布局。

除了这些之外,此类还提供名为 setMargin() 的方法。此方法用于设置 stack pane 内节点的边距。

Example

以下程序是 StackPane 布局的示例。在此示例中,我们按相同顺序插入一个 Circle、一个 Sphere 和一个 Text。将此代码保存在名为 StackPaneExample.java 的文件中。

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Sphere;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class StackPaneExample extends Application {
   @Override
   public void start(Stage stage) {
      //Drawing a Circle
      Circle circle = new Circle(300, 135, 100);
      circle.setFill(Color.DARKSLATEBLUE);
      circle.setStroke(Color.BLACK);

      //Drawing Sphere
      Sphere sphere = new Sphere(50);

      //Creating a text
      Text text = new Text("Hello how are you");

      //Setting the font of the text
      text.setFont(Font.font(null, FontWeight.BOLD, 15));

      //Setting the color of the text
      text.setFill(Color.CRIMSON);

      //setting the position of the text
      text.setX(20);
      text.setY(50);

      //Creating a Stackpane
      StackPane stackPane = new StackPane();

      //Setting the margin for the circle
      stackPane.setMargin(circle, new Insets(50, 50, 50, 50));

      //Adding all the nodes to the pane
      stackPane.getChildren().addAll(circle, sphere, text);

      //Creating a scene object
      Scene scene = new Scene(stackPane, 400, 300);

      //Setting title to the Stage
      stage.setTitle("Stack Pane Example");

      //Adding scene to the stage
      stage.setScene(scene);

      //Displaying the contents of the stage
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

使用以下命令,从命令提示符编译并执行已保存的 java 文件。

javac --module-path %PATH_TO_FX% --add-modules javafx.controls StackPaneExample.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls StackPaneExample

执行后,上述程序会生成如下所示的 JavaFX 窗口。

stackpane output