Reputation: 1359
I am drawing images in paintComponent(Graphics g) method in order to make them compatible with Retina displays
g.drawImage(image, 0, 0, imageWidth/2, imageHeight/2, null);
Everything works perfectly but the image's shadows stack on each other. It makes the picture ugly. So I need to clear image before drawing new. Here comes the problem:
I had no problems clearing image, however the problem is to prevent the background of the parent element from being overlapped. Now it looks in such a way http://cl.ly/image/0K1u0q2M150W .
I used methods from other topics:
g2d.setBackground(new Color(255,255,255,0));
g2d.clearRect(0, 0, ICON_WIDTH, ICON_HEIGHT);
as well as
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
g2d.setBackground(new Color(255,255,255,0));
g2d.clearRect(0, 0, ICON_WIDTH, ICON_HEIGHT);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
and several others.
this is how it should look like http://cl.ly/image/2V1R1v0X452N and this is how it looks after invoking repaint() method several times. I need to call it to change the image from one to another.
my paintComponent method:
Image image;
if (flag) {
image = image1;
} else {
image = image2;
}
g2d.drawImage(image, 0, 0, IMAGE_SIZE, IMAGE_SIZE, null);
Upvotes: 1
Views: 7154
Reputation: 1359
While writing this question I accidentally found the answer. For me calling
super.paintComponent(g);
in the beginning of the paintComponnent() method was the solution. Because it clears the image somewhere inside.
The code from super.paintComponent(g) that clears image is the following:
g.setColor(c.getBackground());
g.fillRect(0, 0, c.getWidth(),c.getHeight());
if I put it instead of super.paintComponent - it also works. I just needed not to set my own color before filling the rectangle.
Upvotes: 6