我觉得你的代码很好。我已经在一个充满图像的文件夹中尝试过你的代码。我把
GridPane
在
ScrollPane
并给ScrollPane一个定义的大小。之间的空间
ImageViews
符合
HGap
和
VGap
假如这是一张图片来支持我的发现。
笔记
如果您正在寻找
ImageView
在一个
网格窗格
使用
setHgap()
和
setVgap()
setPadding()
用于设置网格周围的边距。你当然可以像我下面所做的那样,同时使用这两者
请找到这个
MCVE
帮助你发现错误
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class LoadingImages extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
ScrollPane scrollPane = new ScrollPane();
GridPane gridpane = new GridPane();
scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
scrollPane.setPrefSize(500, 500);
scrollPane.setContent(gridpane);
Scene scene = new Scene(scrollPane);
primaryStage.setScene(scene);
primaryStage.show();
File file = new File("Path to folder with images");
File[] filelist1 = file.listFiles();
ArrayList<File> filelist2 = new ArrayList<>();
for (File file1 : filelist1) {
filelist2.add(file1);
}
List btnar=new ArrayList<>();
for (int i = 0; i < filelist2.size(); i++) {
Button downloadbtn=new Button("Download");
btnar.add(downloadbtn);
}
System.out.println(filelist2.size());
gridpane.setAlignment(Pos.CENTER);
gridpane.setPadding(new Insets(50, 50, 50, 50));
gridpane.setHgap(50);
gridpane.setVgap(50);
ColumnConstraints columnConstraints = new ColumnConstraints();
columnConstraints.setFillWidth(true);
columnConstraints.setHgrow(Priority.ALWAYS);
gridpane.getColumnConstraints().add(columnConstraints);
int imageCol = 0;
int imageRow = 0;
for (int i = 0; i < filelist2.size(); i++) {
System.out.println(filelist2.get(i).getName());
Image image = new Image(filelist2.get(i).toURI().toString());
ImageView pic = new ImageView();
pic.setFitWidth(130);
pic.setFitHeight(130);
pic.setImage(image);
VBox vb = new VBox();
vb.getChildren().addAll(pic,(Button)btnar.get(i));
gridpane.add(vb, imageCol, imageRow);
GridPane.setMargin(pic, new Insets(2,2,2,2));
imageCol++;
// To check if all the 3 images of a row are completed
if (imageCol > 2) {
// Reset Column
imageCol = 0;
// Next Row
imageRow++;
}
}
}
public static void main(String[] args) {
launch(args);
}
}