title: Java Graphics2D Panning and Zooming / Translating and Scaling
body: <p>I've got a JPanel I'm drawing onto and I'm trying to get it so that you can use the mouse wheel to "zoom" in and out by modifying the variable scale.  Right now what happens is you can zoom in or out but all of the drawing shifts to the right and downwards when you zoom in and then back up and left when zooming out.</p>
  
  <p>I want to make it so that it adjusts as if you were zooming in on the point at the center of the JPanel but I can't figure out how to calculate the right offset to translate by… </p>
  
  <p>Anybody got an idea of how to do this, or even better a cleaner way of achieving this whole pan and zoom ability?</p>
  
  <p>I am basically plotting a bunch of coordinates that came from a system where 0,0 is in the lower left corner and fall between the bounds:</p>
  
  <pre><code>xMin = 661208
  xMax = 662618
  
  yMin = 4291657
  yMax = 4293285
  
  @Override
  protected void paintComponent(Graphics g) {
      super.paintComponent(g);
  
      Graphics2D g2 = (Graphics2D) g;
  
      double scale = details.getScale();
      double xOffset = details.getxOffset();
      double yOffset = details.getyOffset();
  
      g2.scale(scale, -scale);
  
      // Dividing offset by scale makes panning 1:1 with the cursor still. yMax to account for the
      // fact we needed to flip around the y axis to make it right-side up.
      g2.translate((-xMin + xOffset / scale), (-yMax + yOffset / scale));
  
      // Code to draw stuff goes here.  It uses coordinates between xMin-xMax and yMin-yMax to draw.
      .
      .
      .
  }
  </code></pre>