在 FXML 中创建动态数量的组件

Creating dynamic amount of components in FXML

我做了一个记事卡程序,可以帮助大家学习JavaFX。它通过 XML 保存 class 并在启动时找到 XML 文件并将它们添加到一个名为 allProjects 的 NoteCardSet 类型的 ArrayList,一个 NoteCards 的 ArrayList。有了这个,我制作了动态数量的按钮,使它们有 4 列宽。这是相关代码:

    int amountPerRow = 4;
    int current = 0;
    int row = 0;

    for (NoteCardSet noteCardSet : allProjects) {

        Button b = new Button(noteCardSet.getName());

        GridPane.setConstraints(b, current, row);
        centerMenu.getChildren().add(b);

        b.setOnAction(e -> {

            border.setCenter(noteCardSetLayout(noteCardSet));
        });

        if (current < amountPerRow - 1)
        {
            current++;
        }
        else if (current >= amountPerRow - 1)
        {
            current = 0;
            row++;
        }
    }

显然这可以在 JavaFX 中创建,但是否可以在 FXML 中创建?

不,您不能在 FXML 中执行此操作。没有办法在fxml中写一个LOOP。如果您只是考虑一个 Button,那么您可以使用 SceneBuilder 并拖放多个按钮。

不过,如果考虑到更复杂的 UI 并想重复它们,您可以创建一个单独的 FXML,并根据需要使用 <fx:include>.

您还可以使用循环多次加载相同的 fxml,并将所有相关数据放入 initialize() 中,但这可能不是您正在寻找的最佳解决方案。