如何使用forloop将图像视图添加到gridpane

如何使用forloop将图像视图添加到gridpane

本文介绍了如何使用forloop将图像视图添加到gridpane的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码。这提示异常说IllegalArgumentException:Children:重复的子项添加:parent = Grid hgap = 5.0,vgap = 5.0,alignment = TOP_LEFT

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"

文件文件=新文件(D:\ SERVER \ Server Content \ Apps\icons);

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

                }


推荐答案

添加商品到 GridPane 有点不同。

应用程序也可以使用便捷方法,这些方法结合了设置的
步骤约束和添加子项

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 ?

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

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

这篇关于如何使用forloop将图像视图添加到gridpane的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 12:23