代码之家  ›  专栏  ›  技术社区  ›  horribly_n00bie

JavaFX:当您使用for循环创建一组标签(如id)时会发生什么?

  •  -1
  • horribly_n00bie  · 技术社区  · 4 年前

    所以,我想开始在VBox中操作元素。我使用加载到fxml行中的for循环按程序添加它们。

    public void scoreRows() {
        AtomicInteger rows = new AtomicInteger(1);
        for (int i = 0; i <= 10; i++) {
            if (rows.get() <=10) {
                HBox scoreCellRow = null;
                try {
                    scoreCellRow = FXMLLoader.load(getClass().getResource("/views/score_cell.fxml"));
                    rowHolder.getChildren().add(scoreCellRow);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("No more rows");
            }
        }
    }
    

    据我所知,每次添加一行时,都会实例化一个新的控制器。所以我想知道如何找到这些元素来定位它们。例如,如果我想通过更改HBox fx:id cellHolder来更改其他行的背景色,该怎么办?或者,如果我想将每行第一个框中的文本更改为顺序标签fx:id roundNum,该怎么办?

    Score sheet example

    0 回复  |  直到 4 年前
        1
  •  0
  •   horribly_n00bie    4 年前

    事实证明,只有三件事是你真正需要的。

    1. 放置物品的地方

    2. FXMLLoader和获取目录

    3. 对象及其控制器一起

      //这是放置物体的地方 HBox scoreCellRow=空;

              try {
                  //This is the FXMLLoader pointing to the directory
                  FXMLLoader loader = new FXMLLoader(getClass().getResource("/views/score_cell.fxml"));
      
                  //Now we can use the Loader that I named "loader" to load the fxml and get the controller
                  scoreCellRow = loader.load();
                  rowHolder.getChildren().add(scoreCellRow);
                  ScoreCellCtrl scoreCellCtrl = loader.getController();
      
                  //Once it's set up changing things as they are added is easy
                  scoreCellCtrl.setRoundNum(String.valueOf(adjustedRnd));
                  if (adjustedRnd % 2 == 0) {
                      scoreCellCtrl.getCellHolder().setStyle("-fx-background-color:#ffe89e;");
      
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
      

    **adjustedRnd是一个int,我与for循环一起使用它来正确标记行,调整我想要在两轮之间插入的任何内容。

    推荐文章