The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)

 < Day Day Up > 

How to Make Frames (Main Windows )

A frame, implemented as an instance of the JFrame class, [62] is a window that typically has decorations such as a border, a title, and buttons for closing and iconifying itself. Applications with a GUI typically use at least one frame. Applets sometimes use frames as well.

[62] JFrame API documentation is on the CD and online at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFrame.html.

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

[63] See How to Make Dialogs (page 187).

[64] See How to Use Internal Frames (page 245).

Creating and Showing Frames

Figure 23 is a picture of an extremely plain window created by an example called Frame-Demo . You can run FrameDemo using Java Web Start or compile and run the example yourself. [65]

[65] To run FrameDemo using Java Web Start, click the FrameDemo link on the RunExamples/ components .html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#FrameDemo .

Figure 23. The FrameDemo application.

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);

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

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.

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 because it has only one frame and closing it makes the program useless. See Responding to Window-Closing Events (page 240) for details.

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 (page 48) in Chapter 3.

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

The pack method sizes the frame so that all of 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, pack is preferable to calling setSize , since it 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 set-LocationRelativeTo or the setLocation method. For example, the following code centers a frame onscreen:

frame.setLocationRelativeTo(null);

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

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, a feature typically used with full-screen exclusive mode. [66] (If you want a smaller-than-full-screen window without decorations, you should use the JWindow or Window class instead.)

[66] Refer to the "Full-Screen Exclusive Mode" trail in The Java Tutorial on the CD and online at: http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html.

Besides specifying how the window decorations are provided, you can also specify which icon is used the represent the window. Exactly how this icon is used depends on the window system or look and feel that provides the window decorations. If the window system supports minimization, the icon is used to represent the minimized window. Most window systems or look and feels also display the icon in the window decorations. A typical icon size is 16 x 16 pixels, but some window systems use other sizes.

Figure 24 shows three frames that are identical except for their window decorations. As you can tell by the appearance of the button in each frame, all three use the Java look and feel. However, only the first and third frames use window decorations provided by the Java look and feel. The second uses decorations provided by the window system, which happens to be Microsoft Windows but could as easily have been any other system running the 1.4 version of the Java platform. The third frame uses Java look-and-feel window decorations, but has a custom icon.

Figure 24. (a) Window decorations provided by the look and feel; (b) window decorations provided by the window system; and (c) custom icon with window decorations provided by the look and feel.

Here's an example of creating a frame with a custom icon and with window decorations provided by the look and feel:

//Ask for window decorations provided by the look and feel. JFrame.setDefaultLookAndFeelDecorated(true); //Create the frame. JFrame frame = new JFrame("A window"); //Set the frame's icon to an image loaded from a file. frame.setIconImage(new ImageIcon(imgURL).getImage());

As the code snippet here implies, you must invoke the setDefaultLookAndFeelDecorated method before creating the frame whose decorations you want to affect. The value you set with setDefaultLookAndFeelDecorated is used for all subsequently created JFrame s. You can switch back to window system decorations by invoking JFrame.setDefaultLookAndFeelDecorated(false) . Some look and feels might not support window decorations; in this case, the window system decorations are used.

Version Note: The setDefaultLookAndFeelDecorated method was added in v1.4. Previously, the decorations on a frame were always provided by the window system.

The full source code for the application that creates the frames pictured in Figure 24 is in FrameDemo2.java . [67] Besides showing how to choose window decorations, FrameDemo2 also shows how to disable all window decorations and gives an example of positioning windows.

[67] FrameDemo2.java is included on the CD and is available online. You can find it here: JavaTutorial/uiswing/components/example-1dot4/FrameDemo2.java .

It includes two methods that create the Image objects used as iconsone is loaded from a file and the other is painted from scratch.

Try This:

  1. Run FrameDemo2 using Java Web Start or compile and run the example yourself. [68]

    [68] To run FrameDemo2 using Java Web Start, click the FrameDemo2 link on the RunExamples/components.html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#FrameDemo2 .

  2. Bring up two windows, both with look-and-feel-provided decorations but with different icons. The Java look and feel displays the icons in its window decorations. Depending on your window system, the icons may be used elsewhere to represent the window, especially when the window is minimized.

  3. Bring up one or more windows with window system decorations. See if your window system treats these icons differently.

  4. Bring up one or more windows with no window decorations. Play with the various windows types to see how the window decorations, window system, and frame icons interact.

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, you need to either register a window listener that handles window-closing events or 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 interface (implemented by JFrame , JInternalPane , and JDialog ):

DO_NOTHING_ON_CLOSE

Do nothing 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 class)

Exit the application, using System.exit(0) . This is recommended for applications only. If it's used within an applet, a SecurityException may be thrown. Introduced in version 1.3.

Version Note: As of v1.4, DISPOSE_ON_CLOSE can have results similar to those of 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. For details, see "AWT Threading Issues" in the API documentation: http://java.sun.com/j2se/1.4.2/jcp/beta/apidiffs/java/awt/doc-files/AWTThreadIssues.html.

The default close operation is executed after any window listeners handle the window- closing event. So, for example, if you specify that the default close operation is to dispose of a frame, you can 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, the default close operationdisposing of the framewill execute.

For more information about handling window-closing events, see the section How to Write Window Listeners (page 723) in Chapter 10. Besides handling window-closing events, window listeners can also react to other window state changes, such as iconification and activation.

The Frame API

Tables 29 through 31 list the commonly used JFrame constructors and methods. Other methods you might want to call are defined by the java.awt.Frame , [69] java.awt.Window , [70] and java.awt.Component [71] classes, from which JFrame [72] descends.

[69] Frame API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Frame.html.

[70] Window API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Window.html.

[71] Component API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Component.html.

[72] JFrame API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFrame.html.

Because each JFrame object has a root pane, frames support interposing input and painting behavior in front of the frame's children, placing children on different " layers ," and Swing menu bars. These topics were introduced in Using Top-Level Containers (page 46) in Chapter 3 and are explained in detail in How to Use Root Panes (page 316) later in this chapter.

Table 29. 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 , and EXIT_ON_CLOSE . The first three constants are defined in the WindowConstants interface, which JFrame implements. The constant EXIT_ON_CLOSE is defined in the JFrame class, and was introduced in 1.3.

void setIconImage(Image) Image getIconImage() ( in Frame)

Set or get the icon that represents the frame. Note that the argument is a java.awt.Image object, not a javax.swing.ImageIcon (or any other javax.swing.Icon implementation).

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 or to enable custom window decorations. [a] Introduced in 1.4.

static void setDefaultLookAndFeelDecorated(boolean) static boolean isDefaultLookAndFeelDecorated()

Determine whether subsequently created JFrame s should have their window decorations (such as borders, widgets for closing the window, title) provided by the current look and feel. This is only a hint, as some look and feels may not support this feature. Introduced in 1.4.

[a] Refer to the "Full-Screen Exclusive Mode" trail in The Java Tutorial on this book's CD and online at: http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html.

Table 30. Setting the Window Size and Location

Method

Purpose

void pack() (in Window )

Size the window so that all of 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, invoke this method after the window's size has been set.

Table 31. JFrame 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. 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. Use the frame's layered pane to put components on top of or behind other components.

Examples That Use Frames

Every standalone application in this chapter uses JFrame . The following table lists a few and tells you where each is discussed.

Example

Where Described

Notes

FrameDemo

Creating and Showing Frames (page 236)

Displays a basic frame with one component.

FrameDemo2

Specifying Window Decorations (page 238)

Lets you create frames with various window decorations.

Framework

Creates and destroys windows, implements a menu bar, and exits an application.

ColorChooserDemo

How to Use Color Choosers (page 167)

A subclass of JFrame that adds components to the default content pane.

TableDemo

How to Use Tables (page 388)

A subclass of JFrame that sets the frame's content pane.

LayeredPaneDemo

How to Use Layered Panes (page 258)

Illustrates how to use a layered pane (but not the frame's layered pane).

GlassPaneDemo

The Glass Pane (page 317)

Illustrates the use of a frame's glass pane.

MenuDemo

How to Use Menus (page 277)

Shows how to put a JMenuBar in a JFrame .

 < Day Day Up > 

Категории