Java JFrame size: How to set the JFrame size

Java JFrame FAQ: How do I set the size of a JFrame?

Solution: There are several different ways to set the size of a Java JFrame, but I generally use the setPreferredSize method of the JFrame class in combination with the Java Dimension class, like this:

jframe.setPreferredSize(new Dimension(400, 300));

A JFrame size example

Here's the source code for a complete "JFrame set size" example, showing how to use this setPreferredSize method call in an actual Java program.

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class JFrameSize
{

  public static void main(String[] args)
  {
    // schedule this for the event dispatch thread (edt)
    SwingUtilities.invokeLater(new Runnable()
    {
      public void run()
      {
        displayJFrame();
      }
    });
  }

  static void displayJFrame()
  {
    // create our jframe as usual
    JFrame jframe = new JFrame("JFrame Size Example");
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // set the jframe size and location, and make it visible
    jframe.setPreferredSize(new Dimension(400, 300));
    jframe.pack();
    jframe.setLocationRelativeTo(null);
    jframe.setVisible(true);
  }

}

More JFrame size information

For more information related to setting the JFrame size, see the Javadoc for the Java Window class (which JFrame inherits from). You'll want to look at the Javadoc for these methods (part of which I have shown below):

  • 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. If current window's size is less than minimumSize the size of the window is automatically enlarged to honor the minimum size. If the setSize or setBounds methods are called afterwards with a width or height less than that specified by setMinimumSize the window is automatically enlarged to honor the minimumSize value. Setting the minimum size to null restores the default behavior.
  • setPreferredSize - Sets the preferred size of this component to a constant value. Subsequent calls to getPreferredSize will always return this value. Setting the preferred size to null restores the default behavior.
  • setMaximumSize - Sets the maximum size of this component to a constant value. Subsequent calls to getMaximumSize will always return this value. Setting the maximum size to null restores the default behavior.

Note that some of those methods are actually in the Java Component class.