问题在于add
方法的使用
代替
imagepanel.add(image, 0, 0);
imagepanel.add(image1, 1, 0);
imagepanel.add(image2, 1, 1);
imagepanel.add(image3, 2, 0);
尝试
imagepanel.add(image);
imagepanel.add(image1);
imagepanel.add(image2);
imagepanel.add(image3);
图像将按添加顺序排列
您尚未显示它,但我建议使用JFrame#pack
将框架调整为其内容的首选大小
更新了示例
根据您所追求的效果,您可以通过将其中一个设置为0
.
例如,如果您想先按行布局组件(即从左到右,从上到下),将rows
参数设置为0
将赋予列更多权重/优先级...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestGrid03 {
public static void main(String[] args) {
new TestGrid03();
}
public TestGrid03() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(0, 5, 5, 5));
File[] files = new File("\path\to\your\images").listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
return pathname.isFile() &&
name.endsWith(".png") ||
name.endsWith(".jpg");
}
});
Arrays.sort(files);
int count = 0;
while (count < 6 && count < files.length) {
try {
System.out.println(count + "; " + files[count]);
add(new JLabel(new ImageIcon(ImageIO.read(files[count]))));
} catch (IOException ex) {
ex.printStackTrace();
}
count++;
}
}
}
}