Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing: set JFrame content area size

Tags:

java

swing

jframe

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?

like image 722
igul222 Avatar asked Mar 15 '10 23:03

igul222


People also ask

How do you adjust the size of a swing frame?

Using setSize() you can give the size of frame you want but if you use pack() , it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier. Try removing frame.

How do I change the size of a content pane in Java?

In Java 5 and later this is the easiest method: JFrame frame = new JFrame("Content Pane Size Example"); frame. getContentPane(). setPreferredSize(new Dimension(400, 300)); frame.

How do I change the size of a JFrame in Java?

Change window Size of a JFrame To resize a frame, There is a method JFrame. setSize(int width, int height) which takes two parameters width and height.

What method sets the size of the displayed JFrame?

setSize - Resizes this component so that it has width w and height h. The width and height values are automatically enlarged if either is less than the minimum size as specified by previous call to setMinimumSize. setMinimumSize - Sets the minimum size of this window to a constant value.


3 Answers

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
like image 152
ring bearer Avatar answered Oct 22 '22 15:10

ring bearer


Never mind, I figured it out:

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

    myJPanel.setPreferredSize(new Dimension(500,500));
    add(myJPanel);
    pack();
}
like image 7
igul222 Avatar answered Oct 22 '22 15:10

igul222


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.

like image 27
Michael Avatar answered Oct 22 '22 15:10

Michael