title: Draw Rectanlge perfectly centered in Java
body: <p>i want to draw objects (incl. putting components) in a container drawn perfectly in the middle.</p>
  
  <p>The problem is, using the middle x and y and subtracting/adding the half of the windows width and height is not enough.</p>
  
  <p>When i draw a rectangle using this code:</p>
  
  <pre><code>g.drawRect( 10, 10, this.getWidth() - 20, this.getHeight() - 20);
  </code></pre>
  
  <p>Then this wont work. With the line above i want to draw a rectangle having a padding of 10 pixels on all sides.
  So i start it at 10x10, then i take the full width and full height of the window and subtract 20 of it, because 10 on the left side and 10 on the right side.</p>
  
  <p>In this case i should get a rectangle which is perfectly centered having 10 pixels distance to the windows border.</p>
  
  <p>But the right and bottom side of the rectangle is out of the window, so the width and the height given to the drawRect method is too high.</p>
  
  <p>I think this comes from the windows border.
  The point 0x0 is not the point where you SEE the drawings. I guess 0x0 starts at the very top-left point of the window itself (no the drawing area).</p>
  
  <p>So in this case i need to know the drawing area. Something like a rectangle giving me coordinates where i need to start drawing, so i can map my coordinates to the windows coordinates.</p>
  
  <p>So when i want to draw a point at 0x0 (of the visible drawing area), then this point must be mapped to something like 8x30.</p>
  
  <p>I did a test by adding a mouse listener printing the mouse position whenever the mouse is moved. When i move my mouse to the very top-left position of the drawing area, then my app prints the coord 8x30. this means the left border has 8px width and the top bar (showing the windows title and close/minimize buttons) has 30px height.</p>
  
  <p>How can i get this working now. I would like to say something like </p>
  
  <pre><code>g.drawRect( 10, 10, this.getWidth() - 20, this.getHeight() - 20);
  </code></pre>
  
  <p>so i get my rectangle drawn perfectly centered even when i resize my window.</p>
  
  <p>I think its easier to understand my problem when you try to paint this: </p>
  
  <pre><code>Font font = g.getFont(); 
  FontRenderContext frc = g.getFontMetrics().getFontRenderContext(); 
  Rectangle2D rect = font.getStringBounds( "Hello", frc); 
  g.drawString( "Hello", (int) ( this.getWidth() - rect.getWidth()), (int) ( this.getHeight() - rect.getHeight())); 
  </code></pre>
  
  <p>This takes the size of the Text "Hello" then tries to print it at the bottom-right. The code is correct, but the Text "Hello" appears to far on the bottom-right, i need to resize my window (making it bigger) to see the text.</p>