I'm trying to create a program in Java that would display set of images one after another adjusting the size of the frame for each one. I'm extending JPanel to display an image like this:
public class ImagePanel extends JPanel{
String filename;
Image image;
boolean loaded = false;
ImagePanel(){}
ImagePanel(String filename){
loadImage(filename);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(image != null && loaded){
g.drawImage(image, 0, 0, this);
}else{
g.drawString("Image read error", 10, getHeight() - 10);
}
}
public void loadImage(String filename){
loaded = false;
ImageIcon icon = new ImageIcon(filename);
image = icon.getImage();
int w = image.getWidth(this);
int h = image.getHeight(this);
if(w != -1 && w != 0 && h != -1 && h != 0){
setPreferredSize(new Dimension(w, h));
loaded = true;
}else{
setPreferredSize(new Dimension(300, 300));
}
}
}
Then in event thread I'm doing main work:
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
createGUI();
}
});
In createGUI() I'm going through the set of images:
ImagePanel imgPan = new ImagePanel();
add(imgPan);
for(File file : files){
if(file.isFile()){
System.out.println(file.getAbsolutePath());
imgPan.loadImage(file.getAbsolutePath());
pack();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The problem is that my program does the resizing properly, so images are loaded correctly but it doesn't display anything. If I display only 1 image it works also it works for the last image. I think the problem is that Thread.sleep() is called before image painting is finished.
How can I wait for my ImagePanel to finish painting and start waiting after that? Or is there another way to solve the problem?
Thanks! Leonty