从布局手册:
JavaFX应用程序可以通过设置每个UI元素的位置和大小属性来手动布局UI.但是,更容易的选择是使用布局窗格.JavaFX SDK提供了几个布局窗格,可以轻松设置和管理经典布局,如行,列,堆栈,磁贴等.在调整窗口大小时,布局窗格会根据节点的属性自动重新定位和调整其包含的节点的大小.
javaFX中有6个面板,例如:BorderPane,StackPane,GridPane,FlowPane,TilePane和AnchorPane.
StackPane堆栈窗格允许您将多个节点放在另一个节点之上.
StackPane root = new StackPane(); Button btn1 = new Button(" 1 "); Button btn2 = new Button("22222222"); root.getChildren().addAll(btn2, btn1); root.setStyle("-fx-background-color: #87CEFA;");GridPane
GridPane允许您创建灵活的行和列网格,并将每个节点放在准确的位置.
GridPane grid = new GridPane(); grid.setPadding(new Insets(10, 10, 10, 10)); grid.setMinSize(300, 300); grid.setVgap(5); grid.setHgap(5); Text username = new Text("Username:"); grid.add(username, 0, 0); TextField text = new TextField(); text.setPrefColumnCount(10); grid.add(text, 1, 0); Text password = new Text("Password:"); grid.add(password, 0, 1); TextField text2 = new TextField(); text2.setPrefColumnCount(10); grid.add(text2, 1, 1); grid.setStyle("-fx-background-color: #D8BFD8");FlowPane
Flow Pane按照添加的顺序依次放置所有节点.
FlowPane flow = new FlowPane(); flow.setPadding(new Insets(10, 10, 10, 10)); flow.setStyle("-fx-background-color: DAE6F3;"); flow.setHgap(5); flow.getChildren().addAll(left, center);TilePane
TilePane类似于流动窗格.所有节点都按照添加的顺序放置在网格中.
TilePane tile = new TilePane(); tile.setPadding(new Insets(10, 10, 10, 10)); tile.setPrefColumns(2); tile.setStyle("-fx-background-color: #CD5C5C;"); HBox hbox2 = new HBox(8); // spacing = 8 hbox2.getChildren().addAll(top, left, center); tile.getChildren().add(hbox2);AnchorPane
AnchorPane允许您在窗格的顶部,底部,左侧,右侧或中心定位节点.
AnchorPane anchorpane = new AnchorPane(); Button buttonSave = new Button("Save"); Button buttonCancel = new Button("Cancel"); anchorpane.setStyle("-fx-background-color: #A9A9A9;"); HBox hb = new HBox(); hb.getChildren().addAll(buttonSave, buttonCancel); anchorpane.getChildren().addAll(hb); anchorpane.setMinSize(300, 100); AnchorPane.setRightAnchor(hb, 10.0);BorderPane
BorderPane将场景分为五个区域,例如:top,bottom,left,right和center.您可以在哪里调整添加的节点.BorderPane还允许您在每个区域中添加不同的窗格,如我的示例所示.但是,您不能多次使用同一窗格.
BorderPane pane = new BorderPane(); pane.setLeft(anchorpane); pane.setCenter(root); pane.setRight(grid); pane.setTop(flow); pane.setBottom(tile); Scene scene = new Scene(pane, 300, 250);