JPanel doesn't update until resize Jframe

nautilusvn picture nautilusvn · Jun 17, 2012 · Viewed 42k times · Source

I subclass JPanel to overwrite paintComponent(Graphics), I want to draw an image onto jpanel in a jframe.

But my image hasn't shown up until I make a change to jframe's size. This is my code:

public class ImagePanel extends JPanel{

    public void setImage(BufferedImage bi)
    {
        image = bi;
        revalidate();
    }

    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        if(image != null)
        {
            g.drawImage(image, 0, 0, this);
        }
    }
}

Answer

trashgod picture trashgod · Jun 17, 2012

Verify that you invoke setVisible() after adding components and calling pack(), as discussed in this related example. You may also need to adopt an appropriate layout. Invoking repaint(), as suggested here, may fix the symptom but not the underlying cause.