Sheen D
Sheen D

Reputation: 11

Java swing won't display g.drawImage() until repaint() is called

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);

    g2.fillRect(20, 20, 200, 200);
    g2.drawImage(map, 0, 0, 1004, 687, null);
}

This is the code for the paintComponent in my JPanel.

When the application is launched, I can see the rectangle (which is only there because I wanted to check if paintComponent was being called). But the map doesn't draw until I force a repaint by resizing the window or pressing a button that forces repaint().

I tried calling validate() in several places because some answers suggested that, but it didn't work.

Upvotes: 0

Views: 366

Answers (1)

camickr
camickr

Reputation: 324157

g2.drawImage(map, 0, 0, 1004, 687, null);

Try using:

g2.drawImage(map, 0, 0, 1004, 687, this);

Maybe the image isn't completely read at the time the paintComponent() method is invoked. The "this" will cause the image to be painted when the I/O is finished. That is the panel will be notified that I/O is done and the panel will repaint itself.

Upvotes: 5

Related Questions