Search code examples
loopsjavafxgridpane

how to add imageviews to gridpane using a forloop


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

                }

Solution

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