JavaFX - BorderPane 佈局



如果我們使用 BorderPane,節點將排列在頂部、左側、右側、底部和中心位置。

名為 BorderPane 的類(位於 javafx.scene.layout 包中)表示 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() 為此屬性設定值。

除此之外,此類還提供以下方法:

  • 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);  
      
      //Setting title to the Stage
      stage.setTitle("BorderPane 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 BorderPaneExample.java 
java BorderPaneExample

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

BorderPane
javafx_layout_panes.htm
廣告

© . All rights reserved.