I am trying to create a program in Java that will display many images one by one, changing the frame size for each of them. I am expanding a JPanel to display an image as follows:
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 the event flow, I do the main work:
SwingUtilities.invokeLater(new Runnable(){ @Override public void run(){ createGUI(); } });
In createGUI () I am looking at a 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) {
The problem is that my program resizes correctly, so the images load correctly, but do not display anything. If I show only 1 image, it works and works for the last image. I think the problem is that Thread.sleep () is called before the image is finished drawing.
How can I wait until my ImagePanel finishes drawing and starts to wait after that? Or is there another way to solve the problem?
Thanks! Leonty
source share