如何使用 JavaFX 创建 StackPane?
在创建了应用程序所需的所有节点后,可以使用布局来对这些节点进行排列。其中,布局是一个计算对象在给定空间中的位置的过程。JavaFX 在 javafx.scene.layout 包中提供了各种布局。
Stack Pane
在此布局中,节点从下到上(一个叠在一个上面)像栈一样排列。可以通过实例化 javafx.scene.layout.StackPane 类在应用程序中创建一个堆栈窗格。
可以使用 setAlignment() 方法设置此窗格中节点的对齐方式。
同样,可以使用 setMatgin() 方法设置窗格内节点的边距。
要向此窗格添加节点,可以将它们作为构造函数的参数传递,或者将它们添加到窗格的可观察列表,如下所示 -
getChildren().addAll();
示例
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.CullFace;
import javafx.scene.shape.DrawMode;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.Sphere;
public class StackedPaneExample extends Application {
public void start(Stage stage) {
//Drawing sphere1
Sphere sphere1 = new Sphere(80);
sphere1.setDrawMode(DrawMode.LINE);
//Drawing sphere2
Sphere sphere2 = new Sphere();
//Setting the properties of the Box(cube)
sphere2.setRadius(120.0);
//Setting other properties
sphere2.setCullFace(CullFace.BACK);
sphere2.setDrawMode(DrawMode.FILL);
PhongMaterial material = new PhongMaterial();
material.setDiffuseColor(Color.BROWN);
sphere2.setMaterial(material);
//Setting the perspective camera
PerspectiveCamera cam = new PerspectiveCamera();
cam.setTranslateX(-50);
cam.setTranslateY(25);
cam.setTranslateZ(0);
//Drawing the shape
MoveTo moveTo = new MoveTo(208, 71);
LineTo line1 = new LineTo(421, 161);
LineTo line2 = new LineTo(226,232);
LineTo line3 = new LineTo(332,52);
LineTo line4 = new LineTo(369, 250);
LineTo line5 = new LineTo(208, 71);
//Creating a Path
Path path = new Path(moveTo, line1, line2, line3, line4, line5);
path.setFill(Color.DARKCYAN);
path.setStrokeWidth(8.0);
path.setStroke(Color.DARKSLATEGREY);
//.setMaterial(material);
//Creating a stack pane
StackPane stackPane = new StackPane();
//Setting the margin for the circle
stackPane.setMargin(sphere2, new Insets(50, 50, 50, 50));
//Retrieving the observable list of the Stack Pane
ObservableList list = stackPane.getChildren();
//Adding all the nodes to the pane
list.addAll(sphere2, sphere1, path);
//Setting the Scene
Scene scene = new Scene(stackPane, 595, 300);
scene.setCamera(cam);
stage.setTitle("Stack Pane");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP