title: Clear image with transparent background in java
body: <p>I am drawing images in paintComponent(Graphics g) method in order to make them compatible with Retina displays</p>
  
  <pre><code>g.drawImage(image, 0, 0, imageWidth/2, imageHeight/2, null);
  </code></pre>
  
  <p>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:</p>
  
  <p>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 <a href="http://cl.ly/image/0K1u0q2M150W" rel="nofollow">http://cl.ly/image/0K1u0q2M150W</a> .</p>
  
  <p>I used methods from other topics:</p>
  
  <pre><code>g2d.setBackground(new Color(255,255,255,0));
  g2d.clearRect(0, 0, ICON_WIDTH, ICON_HEIGHT);
  </code></pre>
  
  <p>as well as </p>
  
  <pre><code>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));
  </code></pre>
  
  <p>and several others.</p>
  
  <p>this is how it should look like <a href="http://cl.ly/image/2V1R1v0X452N" rel="nofollow">http://cl.ly/image/2V1R1v0X452N</a>
  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. </p>
  
  <p>my paintComponent method:</p>
  
  <pre><code>Image image;
  if (flag) {
      image = image1;
  } else {
      image = image2;
  }
  
  g2d.drawImage(image, 0, 0, IMAGE_SIZE, IMAGE_SIZE, null);
  </code></pre>