JFrame Size

I set the size of my JFrame to 1000x500 but it is obvious to me through the use of my drawing methods that the actual size is not 1000x500 but something slightly smaller. Why is this?


JFrame frame = new JFrame("Jumper");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(1000, 500);
frame.add(new Game());
frame.setVisible(true);

It’s because the JFrame has what is called ‘Decorations’. These are the portions of the window that are given over to the L&F or the System to paint the bars on top and on the bottom. These will differ depending on the L&F and the system that the game is being run on, so you should not assume that figuring out manually will result in the same thing every time!

Better would be to…


JFrame frame = new JFrame("Jumper");
JComponent component  = new JComponent();
frame.add(component);
component.setSize(1000,500);
component.add(new Game());
frame.setVisible(true);

Frame.getInsets().top, left, bottom and right gives you the pixel values of the borders

Use Insets as Cero mentioned:


JFrame frame = new JFrame("Jumper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Game());
frame.setVisible(true);

Insets i = frame.getInsets(); //you have to get the Insets after you set the frame visible.
frame.setSize(1000 + i.left + i.right, 500 + i.top + i.bottom);

Sadly, the examples above are wrong.


JComponent component  = new JComponent();
@@component.setPreferredSize(new Dimension(1000,500));
component.add(new Game());

JFrame frame = new JFrame("Jumper");
@@frame.setLayout(new BorderLayout());
@@frame.add(component, BorderLayout.CENTER);
@@frame.pack();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // center on screen
frame.setVisible(true);

This will also resize the component when the frame is resized.

And all wrapped up in a SwingUtilities.invokeLater().

Wow, lots of replies! I’m not sure who’s solution I like the best. ::slight_smile:

Those two lines are unnecessary since a JFrame’s default layout is BorderLayout. All you need is frame.add(component);

Also, don’t draw on a JPanel! I’m trying to eradicate this practice T____T

What should I draw on then?

Using Swing: JComponent.
Pure and raw game: Canvas.

JComponent!

Like was stated earlier.

JFrame should only be used as a frame, a container for your other stuff. Painting should always be done on something else that’s just for painting. Like a dedicated JComponent. :3

Fair enough, but I think his point was that there’s no need to manually account for the insets of the frame, rather you should just set the size of your content pane, since that’s what you’ll render to.

When not doing games I usually used frame.setContentPane(myPanel) since myPanel was always some Container subclass. Saves on one nested component!!!!!!!!!!!!1