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 Dialogs

Several classes support dialogs -- windows that are more limited than frames. To create simple, standard dialogs, you use the JOptionPane(in the API reference documentation) class. The ProgressMonitor class can put up a dialog that shows the progress of an operation. Two other classes, JColorChooser and JFileChooser, also supply standard dialogs. To bring up a print dialog, you can use either the getPrintJob method defined in the Toolkit(in the API reference documentation) class or, if you're using the Java 2 platform, the Printing(in the Creating a GUI with JFC/Swing trail) API. To create custom dialogs, use the JDialog(in the API reference documentation) class directly.

The code for simple dialogs can be minimal. For example, here's an informational dialog:

An informational dialog requires minimal code

Here is the code that creates and shows it:

JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.");
The rest of this section covers the following topics:

An Overview of Dialogs

Every dialog is dependent on a frame. When that frame is destroyed, so are its dependent dialogs. When the frame is iconified, its dependent dialogs disappear from the screen. When the frame is deiconified, its dependent dialogs return to the screen. The AWT automatically provides this behavior.

A dialog can be modal. When a modal dialog is visible, it blocks user input to all other windows in the program. The dialogs that JOptionPane provides are modal. To create a non-modal dialog, you must use the JDialog class directly.

The JDialog class is a subclass of the AWT java.awt.Dialog(in the API reference documentation) class. It adds to Dialog a root pane and support for a default close operation. These are the same features that JFrame has, and using JDialog directly is very similar to using JFrame directly. If you're going to use JDialog directly, then you should understand the material in Using Top-Level Containers and How to Make Frames, especially Responding to Window-Closing Events.

Even when you use JOptionPane to implement a dialog, you're still using a JDialog behind the scenes. The reason is that JOptionPane is simply a container that can automatically create a JDialog and add itself to the JDialog's content pane.

The DialogDemo Example

Here's a picture of an application that displays dialogs.

DialogDemo lets you bring up many kinds of dialogs


Try this: 
  1. Compile and run the application. The main source file is DialogDemo.java(in a .java source file). You will also need one other source file and an image file. See the examples index for links to all the files required by this example.
    See Getting Started with Swing if you need help compiling or running this application.
  2. Click the Show it! button.
    A modal dialog will appear. Until you close it, the application will be unresponsive, although it will repaint itself if necessary. You can close the dialog either by clicking a button in the dialog or explicitly, such as by using the dialog's window decorations.
  3. Iconify the DialogDemo window while a dialog is showing.
    The dialog will disappear from the screen until you deiconify the DialogDemo window.
  4. In the More Dialogs pane, click the bottom radio button and then the Show it! button. A non-modal dialog will appear. Note that the DialogDemo window remains fully functional while the non-modal dialog is up.

JOptionPane Features

Using JOptionPane, you can create and customize several different kinds of dialogs. JOptionPane provides support for laying out standard dialogs, providing icons, specifying the dialog's title and text, and customizing the button text. Other features allow you to customize the components the dialog displays and specify where the dialog should appear onscreen. You can even specify that an option pane put itself into an internal frame (JInternalFrame) instead of a JDialog.

Note:  The internal frames that JOptionPane creates currently behave differently from modal dialogs. They don't behave modally, and in general seem more like frames than like dialogs. For this reason, we don't currently recommend their use.

When you create a JOptionPane, look-and-feel-specific code adds components to the JOptionPane and determines the layout of those components.

JOptionPane's icon support lets you easily specify which icon the dialog displays. You can use a custom icon, no icon at all, or any one of four standard JOptionPane icons (question, information, warning, and error). Each look and feel has its own versions of the four standard icons. The following figure shows the icons used in the Java Look & Feel.

Icons provided by JOptionPane
(Java Look & Feel shown)
The Java Look & Feel icon for dialogs that ask questions The Java Look & Feel icon for informational dialogs The Java Look & Feel icon for warning dialogs The Java Look & Feel icon for error dialogs
question information warning error

Creating and Showing Simple Dialogs

For most simple modal dialogs, you create and show the dialog using one of JOptionPane's showXxxDialog methods. If your dialog should be an internal frame, then add Internal after show -- for example, showMessageDialog changes to showInternalMessageDialog. If you need to control the dialog's window-closing behavior or if the dialog isn't modal, then you should directly instantiate JOptionPane and add it to a JDialog instance. Then invoke setVisible(true) on the JDialog to make it appear.

The two most useful showXxxDialog methods are showMessageDialog and showOptionDialog. The showMessageDialog method displays a simple, one-button dialog. The showOptionDialog method displays a customized dialog -- it can display a variety of buttons with customized button text, and can contain a standard text message or a collection of components.

The other two showXxxDialog methods are used less often. The showConfirmDialog method asks the user to confirm something, but has the disadvantage of having standard button text (Yes/No or the localized equivalent, for example), rather than button text customized to the user's situation (Start/Cancel, for example). A fourth method, showInputDialog, is designed to display a modal dialog that gets a string from the user, using either a text field or an uneditable combo box. However, input dialogs aren't very useful right now, since the text field doesn't let you perform validation before the dialog goes away, and combo boxes in dialogs don't yet work well.

Here are some examples, taken from DialogDemo.java(in a .java source file), of using showMessageDialog, showOptionDialog, and the JOptionPane constructor. For more example code, see DialogDemo.java(in a .java source file) and the other programs listed in Examples that Use Dialogs.

showMessageDialog
Displays a modal dialog with one button, which is labeled "OK" (or the localized equivalent). You can easily specify the message, icon, and title that the dialog displays. Here are some examples of using showMessageDialog:

Informational dialog with default title and icon
//default title and icon
JOptionPane.showMessageDialog(frame,
    "Eggs aren't supposed to be green.");
Informational dialog with custom title, warning icon
//custom title, warning icon
JOptionPane.showMessageDialog(frame,
    "Eggs aren't supposed to be green.",
    "Inane warning",
    JOptionPane.WARNING_MESSAGE);
Informational dialog with custom title, error icon
//custom title, error icon
JOptionPane.showMessageDialog(frame,
    "Eggs aren't supposed to be green.",
    "Inane error",
    JOptionPane.ERROR_MESSAGE);
Informational dialog with custom title, no icon
//custom title, no icon
JOptionPane.showMessageDialog(frame,
    "Eggs aren't supposed to be green.",
    "A plain message",
    JOptionPane.PLAIN_MESSAGE);
Informational dialog with custom title, custom icon
//custom title, custom icon
JOptionPane.showMessageDialog(frame,
    "Eggs aren't supposed to be green.",
    "Inane custom dialog",
    JOptionPane.INFORMATION_MESSAGE,
    icon);

showOptionDialog
Displays a modal dialog with the specified buttons, icons, message, title, and so on. With this method, you can change the text that appears on the buttons of standard dialogs. You can also perform many other kinds of customization.

Yes/No/Cancel (in different words); showOptionDialog
//Custom button text
Object[] options = {"Yes, please",
                    "No, thanks",
                    "No eggs, no ham!"};
int n = JOptionPane.showOptionDialog(frame,
    "Would you like some green eggs to go "
    + "with that ham?",
    "A Silly Question",
    JOptionPane.YES_NO_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,
    options,
    options[2]);

JOptionPane (constructor)
Creates a JOptionPane with the specified buttons, icons, message, title, and so on. You must then add the option pane to a JDialog, register a property-change listener on the option pane, and show the dialog. See Stopping Automatic Dialog Closing for details.

Explicitly used the JOptionPane constructor
final JOptionPane optionPane = new JOptionPane(
    "The only way to close this dialog is by\n"
    + "pressing one of the following buttons.\n"
    + "Do you understand?",
    JOptionPane, QUESTION_MESSAGE,
    JOptionPane.YES_NO_OPTION);

The arguments to all of the showXxxDialog methods and JOptionPane constructors are standardized, though the number of arguments for each method and constructor varies. The following list describes each argument. To see the exact list of arguments for a particular method, see The Dialog API.
Component parentComponent
The first argument to each showXxxDialog method is always the parent component, which must be a frame, a component inside a frame, or null. If you specify a frame, then the dialog will appear over the center of the frame, and depend on that frame. If you specify a component inside a frame, then the dialog will appear over the center of that component, and depend on that component's frame. If you specify null, then the look and feel picks an appropriate position for the dialog -- generally the center of the screen, and the dialog doesn't depend on any visible frame.

The JOptionPane constructors do not include this argument. Instead, you specify the parent frame when you create the JDialog that contains the JOptionPane, and you use the JDialog setLocationRelativeTo method to set the dialog's position.

Object message
This required argument specifies what the dialog should display in its main area. Generally, you specify a string, which results the dialog displaying a label with the specified text. You can split the message over several lines by putting newline (\n) characters inside the message string. For example:
"Complete the sentence:\n \"Green eggs and...\""
String title
The title of the dialog.
int optionType
Specifies the set of buttons that appear at the bottom of the dialog. Choose from one of the following standard sets: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION.
int messageType
This argument determines the icon displayed in the dialog. Choose from one of the following values: PLAIN_MESSAGE (no icon), ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE.
Icon icon
The icon to display in the dialog.
Object[] options
Further specifies the option buttons to appear at the buttom of the dialog. Generally, you specify an array of strings for the buttons. See Customizing Button Text in a Standard Dialog for more information.
Object initialValue
Specifies the default value to be selected.

You can either let the default icon be used or specify the icon using the message type or icon argument. By default, a dialog created with showMessageDialog displays the information icon, and a dialog created with showConfirmDialog or showInputDialog displays the question icon. An option pane created with a JOptionPane constructor displays no icon, by default. To specify that the dialog display a standard icon or no icon, specify the message type. To specify a custom icon, use the icon argument. The icon argument takes precedence over the message type; as long as the icon argument has a non-null value, the dialog displays the specified icon.

Customizing Button Text

When you use JOptionPane to create a dialog, you can choose either to use the standard button text (which might vary by look and feel) or to specify different text.

The following code, taken from DialogDemo.java(in a .java source file), creates two Yes/No dialogs. The first dialog is implemented with showConfirmDialog, which uses the look-and-feel wording for the two buttons. The second dialog uses showOptionDialog so it can customize the wording. With the exception of wording changes, the dialogs are identical.

A yes/no dialog, in those words [but perhaps translated]
//default icon, custom title
int n = JOptionPane.showConfirmDialog(
    frame,
    "Would you like green eggs and ham?",
    "An Inane Question",
    JOptionPane.YES_NO_OPTION);
A yes/no dialog -- in other words
Object[] options = {"Yes, please",
                    "No way!"};
int n = JOptionPane.showOptionDialog(frame,
    "Would you like green eggs and ham?",
    "A Silly Question",
    JOptionPane.YES_NO_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,     //don't use a custom Icon
    options,  //the titles of buttons
    options[0]); //default button title

Getting the User's Input from a Dialog

As the previous code snippets showed, the showMessageDialog, showConfirmDialog, and showOptionDialog methods return an integer indicating the user's choice. The values for this integer are YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, and CLOSED_OPTION. Except for CLOSED_OPTION, each option corresponds to the button the user pressed. When CLOSED_OPTION is returned, it indicates that the user closed the dialog window explicitly, rather than by choosing a button inside the option pane.

Even if you change the strings that the standard dialog buttons display, the return value is still one of the pre-defined integers. For example, a YES_NO_OPTION dialog always returns one of the following values: YES_OPTION, NO_OPTION, or CLOSED_OPTION.

If you're designing a custom dialog, on the other hand, then you need to design your dialog's API so that you can query the dialog about what the user chose. For example, the dialog implemented in CustomDialog.java(in a .java source file) has a getValidatedText method that returns the text the user entered.

Stopping Automatic Dialog Closing

By default, when the user clicks a JOptionPane-created button, the dialog closes. But what if you want to check the user's answer before closing the dialog? In this case, you must implement your own property change listener so that when the user clicks a button, the dialog doesn't automatically close.

DialogDemo contains two dialogs that implement a property change listener. One of these dialogs is a custom modal dialog, implemented in CustomDialog(in a .java source file), that uses JOptionPane both to get the standard icon and to get layout assistance. The other dialog, whose code is below, uses a standard Yes/No JOptionPane, Though this dialog is rather useless as written, its code is simple enough that you can use it as a template for more complex dialogs.

Besides setting the property change listener, the following code also calls the JDialog's setDefaultCloseOperation method and implements a window listener that handles the window close attempt properly. If you don't care to be notified when the user closes the window explicitly, then ignore the bold code.

final JOptionPane optionPane = new JOptionPane(
                "The only way to close this dialog is by\n"
                + "pressing one of the following buttons.\n"
                + "Do you understand?",
                JOptionPane.QUESTION_MESSAGE,
                JOptionPane.YES_NO_OPTION);

final JDialog dialog = new JDialog(frame, 
                             "Click a button",
                             true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(
    JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
        setLabel("Thwarted user attempt to close window.");
    }
});
optionPane.addPropertyChangeListener(
    new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (dialog.isVisible() 
             && (e.getSource() == optionPane)
             && (prop.equals(JOptionPane.VALUE_PROPERTY) ||
                 prop.equals(JOptionPane.INPUT_VALUE_PROPERTY)))
            {
                //If you were going to check something
                //before closing the window, you'd do
                //it here.
                dialog.setVisible(false);
            }
        }
    });
dialog.pack();
dialog.setVisible(true);

int value = ((Integer)optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
    setLabel("Good.");
} else if (value == JOptionPane.NO_OPTION) {
    setLabel("Try using the window decorations "
             + "to close the non-auto-closing dialog. "
             + "You can't!");
}

The Dialog API

The following tables list the commonly used JOptionPane and JDialog constructors and methods. Other methods you're likely to call are defined by the Dialog(in the API reference documentation), Window(in the API reference documentation) and Component(in the API reference documentation) classes and include pack, setSize, and setVisible.

The API is listed as follows:

Showing Standard Modal Dialogs (Using JOptionPane Class Methods)
Method Purpose
int showMessageDialog(Component, Object)
int showMessageDialog(Component, Object, String, int)
int showMessageDialog(Component, Object, String, int, Icon)
Show a one-button, modal dialog that gives the user some information. The arguments specify (in order) the parent component, message, title, message type, and icon for the dialog. See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.
int showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object) Show a customized modal dialog. The arguments specify (in order) the parent component, message, title, option type, message type, icon, options, and initial value for the dialog. See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.
int showConfirmDialog(Component, Object)
int showConfirmDialog(Component, Object, String, int)
int showConfirmDialog(Component, Object, String, int, int)
int showConfirmDialog(Component, Object, String, int, int, Icon)
Show a modal dialog that asks the user a question. The arguments specify (in order) the parent component, message, title, option type, message type, and icon for the dialog. See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.
String showInputDialog(Object)
String showInputDialog(Component, Object)
String showInputDialog(Component, Object, String, int)
String showInputDialog(Component, Object, String, int, Icon, Object[], Object)
Show a modal dialog that prompts the user for input. The single-argument version specifies just the message, with the parent component assumed to be null. The arguments for the other versions specify (in order) the parent component, message, title, message type, icon, options, and initial value for the dialog. See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.
int showInternalMessageDialog(...)
int showInternalOptionDialog(...)
int showInternalConfirmDialog(...)
String showInternalInputDialog(...)
Implement a standard dialog as an internal frame. See the JOptionPane API documentation(in the API reference documentation) for the exact list of arguments.

Methods for Using JOptionPanes Directly
Method or Constructor Purpose
JOptionPane()
JOptionPane(Object)
JOptionPane(Object, int)
JOptionPane(Object, int, int)
JOptionPane(Object, int, int, Icon)
JOptionPane(Object, int, int, Icon, Object[])
JOptionPane(Object, int, int, Icon, Object[], Object)
Creates a JOptionPane instance. See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.
Frame getFrameForComponent(Component)
JDesktopPane getDesktopPaneForComponent(Component)
Handy JOptionPane class methods that find the frame or desktop pane, respectively, that the specified component is in.

Frequently Used JDialog Constructors and Methods
Method/Constructor Purpose
JDialog()
JDialog(Frame)
JDialog(Frame, boolean)
JDialog(Frame, String)
JDialog(Frame, String, boolean)
Creates a JDialog instance. The Frame argument, if any, is the frame (usually a JFrame object) that the dialog depends on. Make the boolean argument true to specify a modal dialog, false or absent to specify a non-modal dialog. You can also specify the title of the dialog, using a string argument.
Container getContentPane()
setContentPane(Container)
Get and set the content pane, which is usually the container of all the dialog's components. See Using Top-Level Containers for more information.
int getDefaultCloseOperation()
setDefaultCloseOperation(int)
Get and set what happens when the user tries to close the dialog. Possible values: DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE (the default). See Responding to Window-Closing Events for more information.
void setLocationRelativeTo(Component) Centers the dialog over the specified component.

Examples that Use Dialogs

This table lists examples that use JOptionPane or JDialog. To find other examples that use dialogs, see the example lists for progress bars, color choosers, and file choosers.

Example Where Described Notes
DialogDemo,
CustomDialog
This section Creates many kinds of dialogs, using JOptionPane and JDialog.
Framework -- Brings up a confirmation dialog when the user selects the Quit menu item.
ListDialog How to Use BoxLayout Implements a modal dialog containing a scrolling list and two buttons. Doesn't use JOptionPane, except for the utility method getFrameForComponent.
TableDemo How to Use Tables Brings up a warning dialog when the user types a non-number entry into a cell that must contain a number.


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