Reputation: 1645
I am trying to learn Swing and have made a panel (with help from other StackOverflow code). I added a checkerboard design on a frame, but I have found that the frame is not as big as it should be.
Here is my code:
@Override
protected void paintComponent(Graphics g) {
int width = getWidth(), height = getHeight();
g.clearRect(0, 0, width, height);
g.setColor(Color.BLACK);
for (int i=0;i<=width;i+=50) {
g.drawLine(0,i,width,i);
}
for (int i=0;i<=height;i+=50) {
g.drawLine(i,0,i,height);
}
label.setText("H = "+ getHeight() +" W = "+ getWidth()); // check actual size
add(label);
}
private void gui(Pan window) {
frame = new JFrame();
Container container = frame.getContentPane();
container.add(window);
frame.setSize(400, 400); // size written here
frame.setVisible(true);
}
If you run it, you'll see the size of the window. It will be 362 by 384, instead of 400 by 400 as written in the code.
If I change the dimensions to 500 by 500, the window will be 462 by 484.
Q: Why are the dimensions off by 38 and 16?
Upvotes: 0
Views: 1035
Reputation: 324088
It will be 362 by 384, instead of 400 by 400
Because the size of the frame include the title bar and borders. Don't use the setSize() method.
Instead override the getPreferredSize()
method of your custom panel to return the size that you want the panel to be.
Then you use:
frame.pack();
Then the size of the frame will be the preferred size of your panel, plus the size of the title bar and borders.
Upvotes: 6