【问题标题】:JavaFx include multiple gui in the main guiJavaFx 在主 gui 中包含多个 gui
【发布时间】:2016-04-06 10:22:22
【问题描述】:

我在使用 SceneBuilder 及其相关控制器创建的 fxml 文件中有一个主 gui。 在那个主 gui 中,我有一个网格窗格,我想为每个单元格放置三个孩子(一个标签、一个 TextView 和一个 CheckBox)。 所以我创建了一个额外的 fxml,其中一个 HBox 作为 root 和三个孩子。

现在...如何通过代码在主 gui 的网格窗格中为每个单元格添加定义的组件并与它们交互?

我的意思是......我想要在主 gui 控制器中做这样的事情:

对于 (int i) 对于(int j) gridpane.add("the_composed_view_in_the_other_fxml", i, j)

【问题讨论】:

    标签: javafx-8 fxml fxmlloader


    【解决方案1】:

    如果我正确理解您的问题,您可以在“主”控制器的 initialize 方法中执行类似操作:

    public class MainController {
    
        @FXML
        private GridPane gridpane ;
    
        public void initialize() throws IOException {
            int numCols = ... ;
            int numRows = ... ;
    
            for (int rowIndex = 0 ; rowIndex < numRows ; rowIndex++) {
                for (int colIndex = 0 ; colIndex < numCols ; colIndex++) {
                    FXMLLoader loader = new FXMLLoader(getClass().getResource("path/to/addtional/fxml"));
                    gridpane.add(loader.load(), colIndex, rowIndex);
                }
            }
        }
    }
    

    对于与从附加 fxml 文件加载的组件进行“交互”,实际上是控制器对附加 fxml 的责任。加载 fxml 文件后,您可以获得对每个控制器的引用:

    gridpane.add(loader.load(), colIndex, rowIndex);
    AdditionalController controller = loader.getController();
    

    然后您可以调用您在该控制器类中定义的方法。你还没有真正提供足够的细节来说明你可能想在这里做什么,但是,例如:

    public class AdditionalController {
    
        @FXML
        private CheckBox checkBox ;
    
        public BooleanProperty selectedProperty() {
            return checkBox.selectedProperty();
        }
    
        // etc...
    }
    

    然后是类似的东西

    gridpane.add(loader.load(), colIndex, rowIndex);
    AdditionalController controller = loader.getController();
    
    String s = String.format("Item [%d, %d]", colIndex, rowIndex);
    controller.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
        if (isNowSelected) {
            // process selection...
            System.out.println(s + " is selected");
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 2019-01-13
      • 2014-12-20
      • 2016-11-15
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多