title: Draw Rectangle Over Buffered Image Java
body: <p>I have a <code>JPanel</code> on which I draw the image of a map using a <code>BufferedImage</code>. I also have a button which, when clicked will highlight a part of the map by drawing a red rectangle over that part. </p>
  
  <p>However, when I zoom in on the image, the rectangle stays where it was before. I assume the reason behind this is that the rectangle is being drawn over the panel and over the Image. </p>
  
  <p>Is there a way to adjust the rectangle's position in accordance with the zoom? </p>
  
  <p>Here's how I draw the rectangle and the image:</p>
  
  <pre><code>//the variable years[activeIndex] is an array which stores my Buffered Images
    Graphics2D g2=(Graphics2D)g.create();
    g.drawImage( years[activeIndex],0, 0,(int)width,(int)height,null);
    g2.setColor(Color.red);
    g2.setStroke(new BasicStroke(3));
    g2.drawRect(this.getWidth()/2,this.getHeight()/2, 20, 20);
    MapViewer.imagePanel.revalidate();
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/oIlfN.jpg" rel="nofollow noreferrer">This is the rectangle when there is no zoom</a></p>
  
  <p><a href="https://i.stack.imgur.com/UKBxQ.png" rel="nofollow noreferrer">This is the rectangle with the zoom, it stays in its place because its on the JPanel and not on the BufferedImage</a></p>