如何使用 JavaFX 建立一個 TilePane?


為應用程式建立所有必需的節點之後,可以使用佈局來排列這些節點。其中,佈局是計算給定空間中物件位置的過程。JavaFX 在 javafx.scene.layout 包中提供了各種佈局。

平鋪面板

在此佈局中,節點以網格形式排列,網格中的圖塊尺寸大小一致。你可以透過例項化 javafx.scene.layout.TilePane 類在應用程式中建立平鋪面板。

  • 在例項化 TilePane 類時,預設會建立一個水平平鋪面板,可以使用 setOrientation() 方法來更改其方向。

  • 可以使用 setMaxWidth() 方法來設定面板的最大寬度。

要向此面板新增節點,你可以將其作為建構函式的引數傳入,或者將它們新增到面板的可觀察列表中,如下所示:

getChildren().addAll();

示例

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;
public class TilePaneExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating buttons
      Button one = new Button("one");
      one.setPrefSize(200, 100);
      Button two = new Button("Two");
      two.setPrefSize(200, 100);
      Button three = new Button("Three");
      three.setPrefSize(200, 100);
      Button four = new Button("Four");
      four.setPrefSize(200, 100);
      Button five = new Button("Five");
      five.setPrefSize(200, 100);
      Button six = new Button("six");
      six.setPrefSize(200, 100);
      Button seven = new Button("seven");
      seven.setPrefSize(200, 100);
      Button eight = new Button("eight");
      eight.setPrefSize(200, 100);
      Button nine = new Button("nine");
      nine.setPrefSize(200, 100);
      //Creating the tile pane
      TilePane tilePane = new TilePane();
      //Setting the orientation for the Tile Pane
      tilePane.setOrientation(Orientation.HORIZONTAL);
      //Setting the alignment for the Tile Pane
      tilePane.setTileAlignment(Pos.CENTER_LEFT);
      //Setting the preferred columns for the Tile Pane
      tilePane.setPrefRows(3);
      //Retrieving the observable list of the Tile Pane
      ObservableList list = tilePane.getChildren();
      //Adding the array of buttons to the pane
      list.addAll(one, two, three, four, five, six, seven, eight, nine);
      //Setting the Scene
      Scene scene = new Scene(tilePane, 600, 300);
      stage.setTitle("Tile Pane");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於:2020-05-19

245 次瀏覽

開啟你的 職業 生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.