The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Using Swing Components

How to Make Frames (Main Windows)

A frame, implemented as an instance of the JFrame (in the API reference documentation) class, is a window that typically has decorations such as a border, a title, and buttons for closing and iconifying the window. Applications with a GUI typically use at least one frame. Applets sometimes use frames, as well.

To make a window that's dependent on another window — disappearing when the other window is iconified, for example — use a dialog instead of a frame. To make a window that appears within another window, use an internal frame.

Creating and Showing Frames

Here's a picture of the extremely plain window created by an example called FrameDemo. You can find the source code in FrameDemo.java (in a .java source file). You can run FrameDemo using Java Web Start (in the Creating a GUI with JFC/Swing trail).

A very boring frame

The following code, taken from FrameDemo, is a typical example of the code used to create and set up a frame.
//1. Optional: Specify who draws the window decorations. 
JFrame.setDefaultLookAndFeelDecorated(true);

//2. Create the frame.
JFrame frame = new JFrame("FrameDemo");

//3. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//4. Create components and put them in the frame.
//...create emptyLabel...
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);

//5. Size the frame.
frame.pack();

//6. Show it.
frame.setVisible(true);
Here are some details about the code:

  1. Calling setDefaultLookAndFeelDecorated(true) requests that any subsequently created frames have window decorations provided by the look and feel, and not by the window system. For details, see Specifying Window Decorations.

  2. The next line of code creates a frame using a constructor that lets you set the frame's title. The other frequently used JFrame constructor is the no-argument constructor.

  3. Next the code specifies what should happen when the user closes the frame. The EXIT_ON_CLOSE operation, not surprisingly, makes the program exit when the user closes the frame. This behavior is appropriate for this program because the program has only one frame, and closing the frame makes the program useless. See Responding to Window-Closing Events for more information.

  4. The next bit of code adds a blank label to the frame's content pane. If you're not already familiar with content panes and how to add components to them, please read Adding Components to the Content Pane.

    For frames that have menus, you'd typically add the menu bar to the frame here using the setJMenuBar method. See How to Use Menus for details.

  5. The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame's size explicitly by calling setSize or setBounds (which also sets the frame's location). In general, using pack is preferable to calling setSize, since pack leaves the frame's layout manager in charge of the frame's size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

    This example doesn't set the frame's location, but it's easy to do so using either the setLocationRelativeTo or setLocation method. For example, the following code centers a frame onscreen:

    frame.setLocationRelativeTo(null);
    

  6. Calling setVisible(true) makes the frame appear onscreen. Sometimes you might see the show method used instead. The two usages are equivalent, but we use setVisible(true) for consistency's sake.

Note:  The pack and setVisible methods realize the frame and the components it contains. Once a component has been realized, any code that modifies or inspects it should be executed on the event-dispatching thread. For more information, refer to Threads and Swing (in the Creating a GUI with JFC/Swing trail).

Specifying Window Decorations

By default, window decorations are supplied by the native window system. However, you can request that the look and feel provide the decorations for a frame. You can even specify that the frame have no window decorations at all (using the setUndecorated method), a feature that is typically used with full-screen exclusive mode (in the Creating a GUI with JFC/Swing trail). If you want a smaller window without decorations, then you probably want to use the JWindow (in the API reference documentation) or Window (in the API reference documentation) class.

The following snapshots show two frames that are identical except for their window decorations. As you can tell by the appearance of the Close window button in each frame, they both use the Java look and feel. However, only the first frame uses window decorations provided by the Java look and feel. The second uses decorations provided by the window system, which happens to be Windows but could as easily be any other platform running the 1.4 version of the Java platform.

A frame with decorations provided by the look and feel A frame with decorations provided by the window system
A frame with look-and-feel-provided decorations A frame with window-system-provided decorations

The difference in window decorations is caused by calls to the JFrame static method setLookAndFeelDecorated, which occur before each frame is created. To use decorations provided by the look and feel, the argument to setLookAndFeelDecorated must be true. To switch back to window system (platform-specific) decorations, the argument must be false. Some look and feels might not support this feature; in this case, the window system decorations are used.


Version Note:  Before 1.4, the decorations on a frame were always provided by the window system and could not be changed.

The source code that creates these frames is in FrameDemo2.java (in a .java source file). You can run FrameDemo2 using Java Web Start (in the Creating a GUI with JFC/Swing trail). Besides showing how to choose window decorations, FrameDemo2 also shows how to disable all window decorations and gives an example of positioning windows.

Responding to Window-Closing Events

By default, when the user closes a frame onscreen, the frame is hidden. Although invisible, the frame still exists and the program can make it visible again. If you want different behavior, then you need to either register a window listener that handles window-closing events, or you need to specify default close behavior using the setDefaultCloseOperation method. You can even do both.

The argument to setDefaultCloseOperation must be one of the following values, the first three of which are defined in the WindowConstants (in the API reference documentation) interface (implemented by JFrame, JInternalPane, and JDialog):

DO_NOTHING_ON_CLOSE
Don't do anything when the user requests that the window close. Instead, the program should probably use a window listener that performs some other action in its windowClosing method.
HIDE_ON_CLOSE (the default for JDialog and JFrame)
Hide the window when the user closes it. This removes the window from the screen but leaves it displayable.
DISPOSE_ON_CLOSE (the default for JInternalFrame)
Hide and dispose of the window when the user closes it. This removes the window from the screen and frees up any resources used by it.
EXIT_ON_CLOSE (defined in the JFrame (in the API reference documentation) class)
Exit the application, using System.exit(0). This is recommended for applications only. If used within an applet, a SecurityException may be thrown. Introduced in 1.3.

Version Note: 
As of 1.4, DISPOSE_ON_CLOSE can have results similar to EXIT_ON_CLOSE if only one window is onscreen. More precisely, when the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate if it is 1.4 or a compatible version. In earlier versions such as 1.3 the VM remains running even when all windows have been disposed of. See bug 4030718 (outside of the tutorial) for details.

[PENDING: When definitive documentation of this issue is released, we will point to it instead of the bug.]


The default close operation is executed after the any window listeners handle the window-closing event. So, for example, assume that you specify that the default close operation is to dispose of a frame. You also implement a window listener that tests whether the frame is the last one visible and, if so, saves some data and exits the application. Under these conditions, when the user closes a frame, the window listener will be called first. If it doesn't exit the application, then the default close operation — disposing of the frame — will then be performed.

For more information about handling window-closing events, see How to Write a Window Listener (in the Creating a GUI with JFC/Swing trail). Besides handling window-closing events, window listeners can also react to other window state changes, such as iconification and activation.

The Frame API

The following tables list the commonly used JFrame constructors and methods. Other methods you might want to call are defined by the java.awt.Frame (in the API reference documentation), java.awt.Window (in the API reference documentation), and java.awt.Component (in the API reference documentation) classes, from which JFrame descends.

Because each JFrame object has a root pane, frames have support for interposing input and painting behavior in front of the frame's children, placing children on different "layers", and for Swing menu bars. These topics are introduced in Using Top-Level Containers and explained in detail in How to Use Root Panes.

The API for using frames falls into these categories:

Creating and Setting Up a Frame
Method or Constructor Purpose
JFrame()
JFrame(String)
Create a frame that is initially invisible. The String argument provides a title for the frame. You can also use setTitle to set a frame's title. To make the frame visible, invoke setVisible(true) on it.
void setDefaultCloseOperation(int)
int getDefaultCloseOperation()
Set or get the operation that occurs when the user pushes the close button on this frame. Possible choices are:
  • DO_NOTHING_ON_CLOSE
  • HIDE_ON_CLOSE
  • DISPOSE_ON_CLOSE
  • EXIT_ON_CLOSE
The first three constants are defined in the WindowConstants (in the API reference documentation) interface, which JFrame implements. The EXIT_ON_CLOSE constant is defined in the JFrame (in the API reference documentation) class, and was introduced in 1.3.
void setUndecorated(boolean)
boolean isUndecorated()
(in Frame)
Set or get whether the window system should provide decorations for this frame. Works only if the frame is not yet displayable (hasn't been packed or shown). Typically used with full-screen exclusive mode (in the Creating a GUI with JFC/Swing trail).
static void setDefaultLookAndFeelDecorated(boolean)
static boolean isDefaultLookAndFeelDecorated()
Determine whether subsequently created JFrames should have their Window decorations (such as borders, widgets for closing the window, title) provided by the current look and feel. Note that this is only a hint, as some look and feels may not support this feature. Introduced in 1.4.

Setting the Window Size and Location
Method Purpose
void pack()
(in Window)
Size the window so that all its contents are at or above their preferred sizes.
void setSize(int, int)
void setSize(Dimension)
Dimension getSize()
(in Component)
Set or get the total size of the window. The integer arguments to setSize specify the width and height, respectively.
void setBounds(int, int, int, int)
void setBounds(Rectangle)
Rectangle getBounds()
(in Component)
Set or get the size and position of the window. For the integer version of setBounds, the window's upper left corner is at the x, y location specified by the first two arguments, and has the width and height specified by the last two arguments.
void setLocation(int, int)
Point getLocation()
(in Component)
Set or get the location of the upper left corner of the window. The parameters are the x and y values, respectively.
void setLocationRelativeTo(Component)
(in Window)
Position the window so that it's centered over the specified component. If the argument is null, the window is centered onscreen. To properly center the window, you should invoke this method after the window's size has been set.

Methods Related to the Root Pane
Method Purpose
void setContentPane(Container)
Container getContentPane()
Set or get the frame's content pane. The content pane contains the frame's visible GUI components and should be opaque.
JRootPane createRootPane()
void setRootPane(JRootPane)
JRootPane getRootPane()
Create, set, or get the frame's root pane. The root pane manages the interior of the frame including the content pane, the glass pane, and so on.
void setJMenuBar(JMenuBar)
JMenuBar getJMenuBar()
Set or get the frame's menu bar to manage a set of menus for the frame.
void setGlassPane(Component)
Component getGlassPane()
Set or get the frame's glass pane. You can use the glass pane to intercept mouse events or paint on top of your program's GUI.
void setLayeredPane(JLayeredPane)
JLayeredPane getLayeredPane()
Set or get the frame's layered pane. You can use the frame's layered pane to put components on top of or behind other components.

Examples that Use Frames

All of the standalone applications in this trail use JFrame. The following table lists a few and tells you where each is discussed.

Example Where Described Notes
FrameDemo The Example Explained Displays a basic frame with one component.
FrameDemo2 Specifying Window Decorations Lets you create frames with various window decorations.
Framework A study in creating and destroying windows, in implementing a menu bar, and in exiting an application.
ColorChooserDemo How to Use Color Choosers A subclass of JFrame that adds components to the default content pane.
TableDemo
[PENDING: when TableDemo is updated to 1.4, this will point to that version]
How to Use Tables A subclass of JFrame that sets the frame's content pane.
LayeredPaneDemo How to Use Layered Panes Illustrates how to use a layered pane (but not the frame's layered pane).
GlassPaneDemo The Glass Pane Illustrates the use of a frame's glass pane.
MenuDemo How to Use Menus Shows how to put a JMenuBar in a JFrame.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2003 Sun Microsystems, Inc. All rights reserved.