欢迎来到Stackoverflow Labib,关于拆分问题:
您可以有一个根FXML,其中包含例如仅GridPane(或其他内容,但我将继续使用GridPane前提),现在您在该根FXML文件中设置网格(无内容),如果您已经有一个完成的GUI,则应该清楚地知道网格单元格需要多大。 在您的主类中,您有:
扩展Application并启动GUI的主类
public class GUI extends Application {
private Stage stage;
private GridPane rootGrid;
@Override
public void start(Stage stage) {
this.stage = stage;
FXMLLoader loader = new FXMLLoader();
loader.setLocation(WindowRoot.class.getResource("RootGrid.fxml"));
rootGrid = (GridPane) loader.load();
Scene scene = new Scene(rootGrid);
stage.setTitle("Test");
stage.show();
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
方法的一部分添加到Grid中。假设您想要在这个简单的例子中添加一个菜单栏。请创建一个用于菜单的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
方法的一部分添加到网格中(但可能需要将其提取为一个方法,您在 start
中调用它,例如 setupGrid()
):
设置网格,在 start(Stage stage) 中调用
private void setupGrid() {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(WindowRoot.class.getResource("menubar.fxml"));
AnchorPane anchor = (AnchorPane) loader.load();
GridPane.setConstraints(anchor, 0, 0);
GridPane.setRowSpan(anchor, 2);
rootGrid.getChildren().add(anchor);
您需要使用try/except IO块,为了更好的可读性,可以将它们省略。对于其他的"Root-Panes",您需要使用其他的设置方法,例如使用borderPane时,您需要类似
rootGrid.setTop(anchor)
这样的语句。
希望这有所帮助,祝您愉快。