minmaxavg
minmaxavg

Reputation: 696

A nested JPanel's background image is not re-drawn correctly

I used ImageIO.read to get image (BackgroundImage) and painted the background image like this :

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);        
    g.drawImage(background, 0, 0, backDim.width, backDim.height, null);
}

and I added some component on that JPanel (background color of the panels inserted into it is new Color(0,0,0,0) (Transparent). The background image is shown correctly when started; however, when I drag it to the bottom edge of the screen, half of them is erased. When I drag it to the left or right edge of the screen, it is re-drawn.

Ahh, and when I removed the Box.createRigidArea() gap, only the background of the titles are shown correctly. Other space is just the default color of a JPanel (light-gray).

EDIT: I added a component listener to make the screen drawn every time I move the window, but it calles repaint frequently so the computer might be overloaded. Is there any other solutions?

EDIT: The problem is that some (or most) of the drawn image is erased when I move the window (which contains the nested JPanel with a background image) to the bottom of the screen and drag it back. However, the repaint() is not called.

Final edit: Solved. It was because I did not call setOpaque(false);

Upvotes: 1

Views: 195

Answers (1)

kleopatra
kleopatra

Reputation: 51524

background color of the panels inserted into it is new Color(0,0,0,0) (Transparent)

A JPanel's opacity is true by default. If you set a transparent background color, you need to set the opacity to false - otherwise you will get painting artefacts (as you experienced)

panel.setBackground(transparentColor);
panel.setOpaque(false);

Upvotes: 4

Related Questions