Creating a window is easy. You just have to create a JFrame
.
JFrame frame = new JFrame();
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!");
//OR
frame.setTitle("Super Awesome Window Title!");
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.
frame.pack();
The setSize()
and pack()
methods are mutually exclusive, so use one or the other.
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.
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
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
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();
frame.setContentPane(pane);
After creating it, you will want to create your components, then show the window. Showing the window is done as such.
frame.setVisible(true);
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