Draw Rectanlge perfectly centered in Java
i want to draw objects (incl. putting components) in a container drawn perfectly in the middle.
The problem is, using the middle x and y and subtracting/adding the half of the windows width and height is not enough.
When i draw a rectangle using this code:
g.drawRect( 10, 10, this.getWidth() - 20, this.getHeight() - 20);
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.
In this case i should get a rectangle which is perfectly centered having 10 pixels distance to the windows border.
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.
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).
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开发者_StackOverflow中文版 to the windows coordinates.
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.
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.
How can i get this working now. I would like to say something like
g.drawRect( 10, 10, this.getWidth() - 20, this.getHeight() - 20);
so i get my rectangle drawn perfectly centered even when i resize my window.
I think its easier to understand my problem when you try to paint this:
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()));
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.
The getInsets()
method of your container should provide the coordinate offsets you need to apply when drawing.
Here is a link to some example code.
Are you drawing directly on the JFrame? It would be easier if you created a JPanel to draw on and added the JPanel to the JFrame. The origin at the top left hand side of the panel will not be bothered by the border of the frame or the title bar.
精彩评论