Swing – Show an Image Grid in JFrame

In this example, We will show you simple Java program about, How to show an Image Grid in JFrame. This example program has been tested and shared in the same post.

Project Structure

Simple Java Program to Show an Image Grid in JFrame

Note: As part of this example, We have used to all countries flag image that can be download from here

Sample Program

package com.dineshkrish;
import java.awt.GridLayout;
import java.awt.Image;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* 
* @author Dinesh Krishnan
*
*/
public class ImageGridExample extends JFrame {
public ImageGridExample(String title) {
super.setTitle(title);
super.setSize(500, 500);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.setVisible(true);
// setting grid layout with rows, cols, hgap, and vgap
super.setLayout(new GridLayout(10, 10, 1, 0));
init();
}
private void init() {
File file = new File("images");
// getting files name from folder
for (String name : file.list()) {
JLabel label = new JLabel();
// setting icon
label.setIcon(new ImageIcon(
new ImageIcon("images/" + name).getImage().getScaledInstance(50, 25, Image.SCALE_DEFAULT)));
add(label);
}
}
public static void main(String[] args) {
new ImageGridExample("Image Grid Example");
}
}

Output

Simple Java Program to Show an Image Grid in JFrame

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *