how to add imageviews to gridpane using a forloop

喜你入骨 提交于 2019-12-24 08:33:16

问题


here's my code.this prompts a exception saying "IllegalArgumentException: Children: duplicate children added: parent = Grid hgap=5.0, vgap=5.0, alignment=TOP_LEFT"

File file = new File("D:\SERVER\Server Content\Apps\icons");

            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);  

                }

回答1:


Adding Items to a GridPane is a little different.

From the Docs

To use the GridPane, an application needs to set the layout constraints on the children and add those children to the gridpane instance. Constraints are set on the children using static setter methods on the GridPane class

Applications may also use convenience methods which combine the steps of setting the constraints and adding the children

So in your example, you first need to decide : How many images do I need in one row ?

Lets say your answer is 4, then your code becomes : (There are diff approaches to it, I am writing down the simplest one. You can use anything, loops for rows and colums being a good alternative ;) )

//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++;
     }
}


来源:https://stackoverflow.com/questions/25357793/how-to-add-imageviews-to-gridpane-using-a-forloop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!