This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
If I have a JFrame object and it's size has been set to a frameWidth of 300 and a frameHeight of 500 and I have a ball (circle) with radius 20 then I intend to draw the circle on the frame using the following
I wish my circle to always be placed "sitting" at the bottom of the frame and to me, it seems logical that this is done by setting my y co-ordinate to be the height of the frame less the radius*2(i.e the height of the circle) so that if I use the following it should be correct (please ignore my random setting for x for now)
have decide to store the co-ordinates in a Point object reference as below so I will eventually pass pos.x and pos.y as my x and y co-ordinates.
but each time I run the form my circle is not visible and is only vsible if I make the y co-ordinate much smaller(shorter). Why is this? Is this not the correct logic or do I have to consider anything else?
do I have to consider anything else? The JFramepaint method is a Container method and draws the container before passing its graphics context to its children which they use to draw themselves. It can draw on top of the containers children.
Check the insets of the JFrame and move your ball up by the bottom inset to clear the lower border.
Don't draw directly on a JFrame for many reasons including loss of double buffering. Instead draw on a JPanel or JComponent, and then place the drawing panel in the JFrame's contentPane (or as a replacement contentPane). Next, please read the Sun graphics tutorials which will explain this and more.
Joined: Apr 04, 2009
I am actually adding a JPanel to a JFrame but when I all getInsets() , I get a value of zero back from the Insets object ref I used with that method, so I still end up with no value to assist me place my circle right on the frame floor with the bottom just touching it.
You have been given the answer. The Insets of a JPanel will be zero. Custom painting is done by overriding the paintComponent() method of the JPanel. So you do your painting relative to the panel. Then you add the panel to the content pane of the frame. Assuming you use the default BorderLayout, the panel will be positioned to take all the available space of the frame.
I wish my circle to always be placed "sitting" at the bottom of the frame and to me, it seems logical that this is done by setting my y co-ordinate to be the height of the frame less the radius*2(i.e the height of the circle) If you are drawing in the frame, yes.
If you are drawing in another component, no. You use the width and height of the component you are drawing in to locate your ball in the component.
The JFrame and the JPanel child are not the same.