【问题标题】:how to add imageviews to gridpane using a forloop如何使用 for 循环将图像视图添加到网格窗格
【发布时间】:2014-08-18 06:57:23
【问题描述】:

这是我的代码。这会提示异常“IllegalArgumentException: Children: duplicate children added: parent = Grid hgap=5.0, vgap=5.0, alignment=TOP_LEFT”

文件 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 之前/之后做什么?

标签: loops javafx gridpane


【解决方案1】:

GridPane 添加项目有点不同。

From the Docs

要使用 GridPane,应用程序需要设置布局 对孩子的约束并将这些孩子添加到网格窗格中 实例。使用静态设置器对子级设置约束 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++;
     }
}

【讨论】:

  • 我正在从目录中添加图像列表。添加后,我的 Scrollpane 变得拥挤。如何保持图像之间的间距?
猜你喜欢
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多