如何使用 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); } }
輸出
廣告