如何使用 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.