Reputation: 3
I am trying to draw some specific graphics onto a JPanel
(which is added onto the JFrame
) like a grid. I am using the length and width of the frame to size the cells on the grid. When the grid is painted, it doesn't fit into the default frame size and I need to re-size the frame manually to be able to see the entire grid. In my example:
I have a 600x600 frame. I want to draw a 20x20 grid. Therefore each frame should be 30x30 pixels across.
I draw the grid and this is what occurs after code completion:
I tried looking for ways to fix this, but everyone says to use frame.pack()
which doesn't work in my case because I'm not using (adding) any JComponent
objects in the panel, it is all custom rendered.
Upvotes: 0
Views: 2224
Reputation: 13
I believe your problem is that when designating dimensions for a JFrame, the compiler takes the size of the borders(insets) from the given dimensions. This results in the display portion of the window being slightly smaller than the dimensions specified. The way to get around this is to add the insets' dimensions to your frame dimensions:
setSize(600+getInsets().right+getInsets().left,600+getInsets().top+getInsets().bottom);
Or if you want to use SetSize(Dimension):
Dimension d = new Dimension(600+getInsets().right+getInsets().left,600+getInsets().top+getInsets().bottom);
setSize(d);
Upvotes: 0
Reputation: 324197
but everyone says to use frame.pack()
Which is correct.
I'm not using (adding) any JComponent objects in the panel, it is all custom rendered.
If you are not adding components to the panel, then you are doing custom painting on the panel. Therefore you need to override the getPreferredSize()
method of your custom painting panel to return the size of the panel, so that the pack() method can work properly.
@Override
public Dimension getPreferredSize()
{
return new Dimension(600, 600);
}
Now when you pack() frame the frame size will be the size of the panel, plus the size of the decorations (title bar, borders) on the frame no matter what OS or LAF you use for your application.
Upvotes: 2