This discussion is archived
1 Reply Latest reply: Aug 26, 2010 1:33 PM by DarrylBurke RSS

Image in panel not available right away?

843810 Newbie
Currently Being Moderated
I'm sure this simple beginner's question has been answered scores of times but I can't find a working explaination.

I have a class, ImagePanel, that extends jPanel.
public class ImagePanel extends JPanel implements Serializable {
    Image image = null;

    public ImagePanel() {
    }

    public ImagePanel(Image image) {
        this.image = image;
    }


    public void setImage(Image image){
        this.image = image;
    }

    public Image getImage(Image image){
        return image;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g); //paint background
        if (image != null) { //there is a picture: draw it
            int height = this.getSize().height;
            int width = this.getSize().width;
            g.drawImage(image,0,0, width, height, this);
            //g.drawImage(image, 0, 0, this); //original image size
         }  //end if
    } //end paint
} //end class
In my main form, I set an image from a file:
   private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
        JFileChooser jFileChooser1 = new JFileChooser();
        jFileChooser1.setCurrentDirectory(new File("."));
        int result = jFileChooser1.showOpenDialog(mainPanel);
        if (result == jFileChooser1.APPROVE_OPTION) {
            String filename = jFileChooser1.getSelectedFile().getAbsolutePath();
            Image image = Toolkit.getDefaultToolkit().getImage(filename);
            imagePanel1.setImage(image);
          
        }
When I first run the program and load an image, the image does not appear. If I deactivate the form then reactivate it, I can see my image.

Thereafter, whenever I load a new image, it appears immediately.

How do I make my loaded image render when I load an image immediately after starting the application?
  • 1. Re: Image in panel not available right away?
    DarrylBurke Guru Moderator
    Currently Being Moderated
    Toolkit loads an image in the background, so it may be some time before the image is completely loaded. ImageIO#read(...) blocks until the image is fully loaded. And yes, it's been answered scores of times.

    Also,even if the image has actually loaded fully, your setImage(...) method doesn't call repaint() so the newly set image would only be painted at the next repaint, which would occur
    If I deactivate the form then reactivate it
    db