swing Using Swing for Graphical User Interfaces Creating an Empty Window (JFrame)


Creating the JFrame

Creating a window is easy. You just have to create a JFrame.

JFrame frame = new JFrame();

Titling the Window

You may wish to give your window a title. You can so do by passing a string when creating the JFrame, or by calling frame.setTitle(String title).

JFrame frame = new JFrame("Super Awesome Window Title!");
frame.setTitle("Super Awesome Window Title!");

Setting the Window Size

The window will be as small as possible when it has been created. To make it bigger, you can set its size explicitly:

frame.setSize(512, 256);

Or you can have the frame size itself based on the size of its contents with the pack() method.


The setSize() and pack() methods are mutually exclusive, so use one or the other.

What to do on Window Close

Note that the application will not quit when the window has been closed. You can quit the application after the window has been closed by telling the JFrame to do that.


Alternatively, you can tell the window to do something else when it is closed.

WindowConstants.DISPOSE_ON_CLOSE //Get rid of the window
WindowConstants.EXIT_ON_CLOSE //Quit the application
WindowConstants.DO_NOTHING_ON_CLOSE //Don't even close the window
WindowConstants.HIDE_ON_CLOSE //Hides the window - This is the default action

Creating a Content Pane

An optional step is to create a content pane for your window. This is not needed, but if you want to do so, create a JPanel and call frame.setContentPane(Component component).

JPanel pane = new JPanel();

Showing the Window

After creating it, you will want to create your components, then show the window. Showing the window is done as such.



For those of you who like to copy and paste, here's some example code.

JFrame frame = new JFrame("Super Awesome Window Title!"); //Create the JFrame and give it a title
frame.setSize(512, 256); //512 x 256px size
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //Quit the application when the JFrame is closed

JPanel pane = new JPanel(); //Create the content pane
frame.setContentPane(pane); //Set the content pane

frame.setVisible(true); //Show the window

Example output