欢迎来到 Stackoverflow Labib,关于分拆:
您可以有一个根 FXML,例如只包含一个 GridPane(或其他,但我将继续在 GridPane 前提下),现在您在该根 FXML 文件中设置网格(无内容),如果您已经完成了 GUI,您应该清楚地知道网格单元需要多大。在您的主类中,您有:
扩展应用程序并启动 GUI 的主类
public class GUI extends Application {
private Stage stage;
private GridPane rootGrid;
@Override
public void start(Stage stage) {
this.stage = stage;
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(WindowRoot.class.getResource("RootGrid.fxml"));
rootGrid = (GridPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootGrid);
stage.setTitle("Test");
stage.show();
//fill the Grid
setupGrid();
}
现在您将rootGrid 作为类属性,它只是一个在RootGrid.fxml 中设置的带有空行/列的网格,可以简单如下:
FXML 示例,两行两列,无内容
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<GridPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.141">
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" />
<RowConstraints minHeight="10.0" prefHeight="30.0" />
</rowConstraints>
<columnConstraints>
<ColumnConstraints minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
</GridPane>
现在您为要填充的每个单元格创建 FXML 文档,并且在该 FXML 中您有一个包含该单元格内容的 AnchorPane。然后将其作为start 方法的一部分添加到网格中。假设您在这个简单的示例中想要一个菜单栏。为菜单创建 FXML:
简单菜单 fxml 示例:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.141">
<children>
<MenuBar>
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
</menus>
</MenuBar>
</children>
</AnchorPane>
并将其作为start 方法的一部分添加到网格中(但可能将其提取到您在开始时调用的方法中,例如setupGrid():
设置 Grid,在 start(Stage stage) 中调用
private void setupGrid() {
// Add Menubar
FXMLLoader loader = new FXMLLoader();
loader.setLocation(WindowRoot.class.getResource("menubar.fxml"));
AnchorPane anchor = (AnchorPane) loader.load();
//put it in first column, first row
GridPane.setConstraints(anchor, 0, 0);
//optional, let it span both/all columns
GridPane.setRowSpan(anchor, 2);
rootGrid.getChildren().add(anchor);
您需要 try/except IO 块,为了更好的可读性,将它们排除在外。对于其他“根窗格”,您将需要其他设置方法,例如使用borderPane,您将拥有rootGrid.setTop(anchor) 之类的东西。
希望能帮助到你。玩得开心。