26

I'm trying to make a JFrame with a usable content area of exactly 500x500. If I do this...

public MyFrame() {
    super("Hello, world!");
    setSize(500,500);
}

... I get a window whose full size is 500x500, including the title bar, etc., where I really need a window whose size is something like 504x520 to account for the window border and titlebar. How can I achieve this?

igul222
  • 8,557
  • 14
  • 52
  • 60

3 Answers3

30

you may try couple of things: 1 - a hack:

public MyFrame(){
 JFrame temp = new JFrame;
 temp.pack();
 Insets insets = temp.getInsets();
 temp = null;
 this.setSize(new Dimension(insets.left + insets.right + 500,
             insets.top + insets.bottom + 500));
 this.setVisible(true);
 this.setResizable(false);
}

2- or Add a JPanel to the frame's content pane and Just set the preferred/minimum size of the JPanel to 500X500, call pack()

  • 2- is more portable
ring bearer
  • 20,383
  • 7
  • 59
  • 72
28

Simply use:

public MyFrame() {
    this.getContentPane().setPreferredSize(new Dimension(500, 500));
    this.pack();
}

There's no need for a JPanel to be in there, if you just want to set the frame's size.

Michael
  • 381
  • 3
  • 3
7

Never mind, I figured it out:

public MyFrame() {
    super("Hello, world!");

    myJPanel.setPreferredSize(new Dimension(500,500));
    add(myJPanel);
    pack();
}
igul222
  • 8,557
  • 14
  • 52
  • 60
  • 2
    In Java 5 it is actually possible to do this without another panel. See http://stackoverflow.com/questions/2796775/setting-the-size-of-a-contentpane-inside-of-a-jframe. – Russ Hayward May 09 '10 at 10:19