JavaFX - StackPane 佈局



JavaFX 中的 StackPane 佈局

StackPane 佈局充當容器,將所有子節點像堆疊一樣疊加在一起。首先新增的節點位於堆疊底部,後續節點位於其頂部。下圖說明了三個矩形框疊加在一起的 StackPane 佈局。它展示了這種佈局型別的創造力潛力。

StackPane

名為 StackPane 的類,位於包 javafx.scene.layout 中,代表 StackPane。此類包含一個名為 alignment 的單個屬性。此屬性表示堆疊面板內節點的對齊方式。

StackPane 類的建構函式列表如下:

  • StackPane() - 這是預設建構函式,它建立一個具有居中對齊方式的空 StackPane 佈局。

  • StackPane(Node childNodes) - 它建立一個具有指定子節點和居中對齊方式的 StackPane 佈局。

除此之外,此類還提供了一個名為 setMargin() 的方法。此方法用於設定堆疊面板內節點的邊距。

示例

以下程式是 StackPane 佈局的示例。在此,我們按順序插入一個圓形、球體和文字。將此程式碼儲存在名為 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
廣告
© . All rights reserved.