如何使用forloop将imageviews添加到gridpane



这是我的代码。这会提示一个异常:"IllegalArgumentException: Children: duplicate Children added: parent = Grid hgap=5.0, vgap=5.0, align =TOP_LEFT"

File File = new File("D:SERVER SERVER ContentAppsicons");

            File[] filelist1 = file.listFiles();
            ArrayList<File> filelist2 = new ArrayList<>();
            hb = new HBox();
            for (File file1 : filelist1) {
                filelist2.add(file1);
            }
            System.out.println(filelist2.size());
                for (int i = 0; i < filelist2.size(); i++) {
                    System.out.println(filelist2.get(i).getName());
                    image = new Image(filelist2.get(i).toURI().toString());
                    pic = new ImageView();
                    pic.setFitWidth(130);
                    pic.setFitHeight(130);
                    gridpane.setPadding(new Insets(5));
                    gridpane.setHgap(5);
                    gridpane.setVgap(5);
                    pic.setImage(image);
                    hb.getChildren().add(pic);  
                }

将项目添加到GridPane有点不同。

From the Docs

要使用GridPane,应用程序需要设置布局子节点上的约束,并将这些子节点添加到网格中实例。使用静态设置器在子对象上设置约束方法

应用程序也可以使用方便的方法来组合这些步骤设置约束并添加子元素

在你的例子中,你首先需要决定:一行需要多少张图片?

假设你的答案是4,那么你的代码变成:(有不同的方法,我写下最简单的一个。你可以使用任何东西,行和列的循环是一个很好的选择;))

//Can be set once, no need to keep them inside loop
gridpane.setPadding(new Insets(5));
gridpane.setHgap(5);
gridpane.setVgap(5);
//Declaring variables for Row Count and Column Count
int imageCol = 0;
int imageRow = 0;
for (int i = 0; i < filelist2.size(); i++) {
     System.out.println(filelist2.get(i).getName());
     image = new Image(filelist2.get(i).toURI().toString());
     pic = new ImageView();
     pic.setFitWidth(130);
     pic.setFitHeight(130);
     pic.setImage(image);
     hb.add(pic, imageCol, imageRow );
     imageCol++;
     // To check if all the 4 images of a row are completed
     if(imageCol > 3){
          // Reset Column
          imageCol=0;
          // Next Row
          imageRow++;
     }
}

最新更新