Ever wondered about how to load multiple images in a folder at the same time?
I was trying to load 2D tile images for my game but loading them one by one was pretty tiresome.
So I tried to find a way to load them simultaneously and this is what I did.
Please check my video tutorial for the details:
Code:
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
BufferedImage [] allImages;
public static void main(String[] args) {
new Main();
}
public Main() {
// If load images from res folder
File path = new File("res");
// If load images in a folder on desktop
// File path = new File("C:\Users\User\Desktop\folder name");
File[] allFiles = path.listFiles();
allImages = new BufferedImage[allFiles.length];
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridLayout(5,5));
JLabel label[] = new JLabel[allFiles.length];
for(int i = 0; i < allFiles.length; i++) {
try{
allImages[i] = ImageIO.read(allFiles[i]);
label[i] = new JLabel();
ImageIcon icon = new ImageIcon(allImages[i]);
label[i].setIcon(icon);
window.add(label[i]);
}catch(IOException e) {
}
}
window.pack();
window.setVisible(true);
}
}
Result:
↓
All the tile images in the folder are loaded and displayed.
No comments:
Post a Comment