JavaFX - BorderPane 佈局



JavaFX 中的 BorderPane 佈局

BorderPane 是一種佈局控制元件,它將 JavaFX 應用程式的所有 UI 元件排列到五個不同的區域,即頂部、左側、右側、底部和中心位置。BorderPane 佈局面板由 javafx.scene.layout 包中的名為 BorderPane 的類表示。例項化此類將建立一個 BorderPane 佈局。此類的建構函式如下:

  • BorderPane() - 它是預設建構函式,建立一個空的 BorderPane。

  • BorderPane(Node centerNode) - 它構建一個新的 BorderPane 佈局並將節點放置在中心。

  • BorderPane(Node center, Node top, Node right, Node bottom, Node left) - BorderPane 類的此引數化建構函式用於使用指定的節點建立新的 BorderPane 佈局。

BorderPane 類包含五個屬性,包括:

  • bottom - 此屬性為 Node 型別,表示放置在 BorderPane 底部的節點。您可以使用 setter 方法 setBottom() 為此屬性設定值。

  • center - 此屬性為 Node 型別,表示放置在 BorderPane 中心的節點。您可以使用 setter 方法 setCenter() 為此屬性設定值。

  • left - 此屬性為 Node 型別,表示放置在 BorderPane 左側的節點。您可以使用 setter 方法 setLeft() 為此屬性設定值。

  • right - 此屬性為 Node 型別,表示放置在 BorderPane 右側的節點。您可以使用 setter 方法 setRight() 為此屬性設定值。

  • top - 此屬性為 Node 型別,表示放置在 BorderPane 頂部的節點。您可以使用 setter 方法 setTop() 為此屬性設定值。

下圖顯示了 JavaFX 節點如何在 BorderPane 佈局中排列:

BorderPane

除了上述屬性和建構函式之外,BorderPane 類還提供以下方法:

  • setAlignment() - 此方法用於設定屬於此窗格的節點的對齊方式。此方法接受一個節點和一個優先順序值。

示例

以下程式是 BorderPane 佈局的示例。在此,我們將五個文字欄位插入到頂部、底部、右側、左側和中心位置。將此程式碼儲存在名為 BorderPaneExample.java 的檔案中。

import javafx.application.Application; 
import javafx.collections.ObservableList; 
import javafx.scene.Scene; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.BorderPane; 
import javafx.stage.Stage; 
         
public class BorderPaneExample extends Application { 
   @Override 
   public void start(Stage stage) {      
      //Instantiating the BorderPane class  
      BorderPane bPane = new BorderPane();   
       
      //Setting the top, bottom, center, right and left nodes to the pane 
      bPane.setTop(new TextField("Top")); 
      bPane.setBottom(new TextField("Bottom")); 
      bPane.setLeft(new TextField("Left")); 
      bPane.setRight(new TextField("Right")); 
      bPane.setCenter(new TextField("Center")); 
      
      //Creating a scene object 
      Scene scene = new Scene(bPane, 400, 300);  
      
      //Setting title to the Stage
      stage.setTitle("BorderPane in JavaFX"); 
         
      //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 BorderPaneExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls BorderPaneExample

輸出

執行後,上述程式生成一個如下所示的 JavaFX 視窗。

BorderPane
廣告