SeanBing
SeanBing

Reputation: 33

JFrame setPreferredSize results in a slightly larger screen size

I was originally using setSize but this resulted in the on screen content being slightly bigger than the screen due to java borders and title room. So I used setpreferredSize and now the screen size is slightly too big. leaving a space around the right and bottom sides of my content.

In my JFrame:

add(new Board());
    setTitle("Rougebot");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    //setSize(600, 800);
    //getContentPane().setPreferredSize(new Dimension(600,800));
    pack();
    setLocationRelativeTo(null);
    setVisible(true);
    setResizable(false);

In my Board (JPanel)

setPreferredSize(new Dimension(600,800));

Upvotes: 1

Views: 2494

Answers (2)

Jason C
Jason C

Reputation: 40335

Call setResizable(false) before calling pack():

add(new Board());
setTitle("Rougebot");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false); // <-- here
pack();
setLocationRelativeTo(null);
setVisible(true);

And continue setting the preferred size of Board, as in the example in your original post.

In Windows, fixed borders are thinner than resizable ones, if you compute sizes then set to fixed size, you change the window border width, which, in Windows, causes the client area to increase and the outer dimensions to remain fixed.

Upvotes: 8

MadProgrammer
MadProgrammer

Reputation: 347214

Frames have decorations (the outer frame). What pack tries to do is make sure that the content (viewable) area meets the requirements of the preferred size of all the child components and then ADDs the frame decoration around it.

The size of the decoration is platform depended

For example...

Upvotes: 1

Related Questions