2

I have had this problem a few times before, and I finally attempted to solve it, but I cannot fond the right solution. I have a simple JFrame program. The basic JFrame code looks like this:

JFrame frame = new JFrame("halp");  
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,500);
    frame.setResizable(false);
    frame.setVisible(true);

Here's an image of what I'm trying to accomplish:

JFrame.

As you can see, there's space taken up by the top bar and the borders of the window. One way to fix this is to increase the size of the window, but that isn't neat at all, and also not every system has the same border sizes of the window.

I've done research and tried a few things I found on earlier asked questions:

  • frame.pack(). This method only set the window to minimal size, as if I didn't set the size at all.
  • frame.getContentPane().setSize(500,500);. The window still has the borders counted in the frame size.
  • frame.setPreferredSize(new Dimension(500, 500)); and JPanel.setPreferredSize(new Dimension(500, 500));. The frame went into minimum size, as with frame.pack().

I tried combining these methods, but nothing seemed to work.

What am I missing? Is there another aspect of the JFrame I need to add? Is it an incompatibility issue of BlueJ?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Quijibo
  • 307
  • 2
  • 13
  • 1
    You can have a look on [this](https://stackoverflow.com/a/12270571/11212670) answer – TehMattGR May 11 '19 at 06:30
  • @TehMattGR Woah, didn't find that question, and I guess I could work out a solution based on that, even though it would be a _very_ ugly solution. I might use it in my programs until I find a better and more neat solution to this. Thanks! – Quijibo May 11 '19 at 07:03
  • 1
    Have you tried `frame.getContentPane().setPreferredSize(new Dimension(500,500))` followed by a `frame.pack()`? – TT. May 11 '19 at 09:29
  • @TT. Just tried it and it worked! I was pretty sure I have tried all possible combinations, but I must've missed this one! My bad. At least I know the optimal way of doing this now. – Quijibo May 11 '19 at 15:06

1 Answers1

2
frame.getContentPane().setPreferredSize(new Dimension(500,500));

followed by a

frame.pack();

should solve your problem.

TT.
  • 15,774
  • 6
  • 47
  • 88