Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Using Swing Components

How to Make Dialogs

Several Swing classes support dialogs -- windows that are more limited than frames. To create simple, standard dialogs, you use JOptionPane(in the API reference documentation). To create custom dialogs, use the JDialog(in the API reference documentation) class directly. 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 use the getPrintJob method method defined in the Toolkit(in the API reference documentation) class [PENDING: check].

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

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. All 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. See How to Make Frames for information about how to add components to a window and how to implement any window listeners. [PENDING: restructure Frame to cover these in a separate section.]

Even if 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.

JOptionPane Features

Using JOptionPane, you can create many dialogs. Here's a sampling, all produced by the DialogDemo example.

As you might guess from the preceding pictures, 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 on-screen. You can even specify that option pane put itself into an internal frame (JInternalFrame) instead of a JDialog.

When you create a JOptionPane, look-and-feel-specific code adds components to the JOptionPane and determines the layout of those components. The following figure shows how the common look and feels lay out a JOptionPane:

icon
(if any)
message
buttons
For most simple modal dialogs, you create and show the dialog using one of JOptionPane's showXxxDialog methods. For examples of using each of the following methods, look at DialogDemo.java. If your dialog should be an internal frame, then add Internal after show -- for example, showInternalMessageDialog.
showMessageDialog
Displays a modal dialog with one button, which is labeled "OK" (or the localized equivalent [PENDING: l10n not implemented yet]). You can easily specify the message, icon, and title that the dialog displays.
showConfirmDialog
Displays a modal dialog with two buttons, labeled "Yes" and "No" (or the localized equivalent [PENDING: l10n not implemented yet]). Those labels aren't always terribly descriptive of whatever program-specific actions they cause. As a result, we generally use option dialogs instead.
showInputDialog
Displays a modal dialog that gets a string from the user. An input dialog either displays a text field for the user to type into, or it displays an uneditable combo box, from which the user can choose one of several strings. [PENDING: Input dialogs aren't very useful right now, since the text field doesn't let you perform validation before the dialog goes away, and the combo box uses a lightweight menu and thus can't display more than 2 or 3 choices.]
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.

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 and Feel (nicknamed Metal).

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

By default, a dialog created with showMessageDialog displays the information icon, and a dialog created with showConfirmDialog or showInputDialog displays the question icon. To specify that a dialog has either no icon or another standard icon, you add a parameter that specifies the message type. The value of the message type can be any of the following constants: PLAIN_MESSAGE (no icon), QUESTION_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, or ERROR_MESSAGE. If you specify a non-null Icon object, then the dialog displays that icon, no matter what the message type is. Here's an example of creating a simple dialog that displays an error message:

JOptionPane.showMessageDialog(frame,
                              "Eggs aren't supposed to be green.",
                              "Inane error",
                              JOptionPane.ERROR_MESSAGE);

Normally, the message area of an option pane has a single line of text, such as "Eggs aren't supposed to be green." 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...\""

You can specify the text displayed by the option pane's buttons. An example of doing so is in Customizing Button Text in Standard Dialogs. When the user clicks any of the option pane's buttons, the dialog is automatically dismissed. If you don't want the dialog to be dismissed automatically -- for example, if you want to make sure that the user's input was valid before dismissing the dialog -- you need to follow the steps described in Stopping Automatic Dialog Dismissal.

When you invoke any of the JOptionPane showXxxDialog methods, the first argument specifies a component. This component determines both the on-screen location of the dialog and the frame upon which the dialog depends. Specifically, the dialog is dependent on the frame that contains the component, and the dialog is centered over the component. If you specify null for the component, then the dialog is independent of any visible frames, and it appears in the middle of the screen. The following figure shows what happens when you specify a JFrame as the first argument.

a dialog centered over a window

The DialogDemo Example

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


Try this:
  1. Compile and run the application. The source file is DialogDemo.java.
    See Getting Started with Swing if you need help.
  2. Click the Show it! button.
    A modal dialog will appear. Until you dismiss it, the application will be unresponsive, although it will repaint itself if necessary. You can dismiss 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.

Customizing Button Text in Standard Dialogs

When you use JOptionPane to create a standard 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, creates two Yes/No dialogs. The first dialog uses the look-and-feel's wording for the two buttons. The second dialog customizes the wording. With the exception of wording changes, the dialogs are identical. To customize the wording, the code that creates the second dialog uses showOptionDialog, instead of showConfirmDialog.

A yes/no dialog

...//create the yes/no dialog:
int n = JOptionPane.showConfirmDialog(
	frame, "Would you like green eggs and ham?",
	"An Inane Question",
	JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
    setLabel("Ewww!");
} else if (n == JOptionPane.NO_OPTION) {
    setLabel("Me neither!");
} else {
    setLabel("Come on -- tell me!");
}
A yes/no dialog -- in other words
...//create the yes/no (but in other words) dialog:
String string1 = "Yes, please";
String string2 = "No way!";
Object[] options = {string1, string2};
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
		string1); //the title of the default button
if (n == JOptionPane.YES_OPTION) {
    setLabel("You're kidding!");
} else if (n == JOptionPane.NO_OPTION) {
    setLabel("I don't like them, either.");
} else {
    setLabel("Come on -- 'fess up!");
}

Getting the User's Input from a Dialog

As the previous example showed, the JOptionPane showXxxDialog methods return a value indicating the user's choice. 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 the simple, standard JOptionPane dialogs, the showXxxDialog methods return an integer. The default 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 in the window.

Even if you change the strings that the standard dialog buttons display (as the previous example shows), 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.

[Add an example of getting input from a custom dialog.]

Stopping Automatic Dialog Dismissal

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

DialogDemo contains two dialogs that implement a property change listener. One of these dialogs is a custom modal dialog, implemented in CustomDialog.java, 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 nonbold 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.show();

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 JComponent(in the API reference documentation) and Component(in the API reference documentation) classes and include [PENDING: anything in particular for dialogs? Make clear that JDialog doesn't extend JComponent]. [Link to JComponent and Component discussions.]

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. See [PENDING: somewhere] for a discussion of the parameters and their effects.
int showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object) Show a dialog. See [PENDING: somewhere] for a discussion of the parameters 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 [PENDING: elaborate]. See [PENDING: somewhere] for a discussion of the parameters 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 an input dialog. See [PENDING: somewhere] for a discussion of the parameters and their effects.
int showInternalMessageDialog(...)
int showInternalOptionDialog(...)
int showInternalConfirmDialog(...)
String showInternalInputDialog(...)
Implement a standard dialog as an internal frame. See [PENDING: somewhere] for a discussion of ....

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. [PENDING: explain the parameters]
Frame getFrameForComponent(Component)
JDesktopPane getDesktopPaneForComponent(Component)
Handy JOptionPane class methods that find the frame or desktop pane, respectively, that the specified component is in.

Other JOptionPane Constructors and Methods
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. [PENDING: explain the parameters]

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 [PENDING: where?] 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 [PENDING: where?] for more information.
void setLocationRelativeTo(Component) Centers the dialog over the specified component.

Examples that Use Dialogs

This table lists examples that use dialogs and where those examples are described.

Example Where Described Notes
DialogDemo.java,
CustomDialog.java
This page Creates many kinds of dialogs, using JOptionPane and JDialog.
Framework.java Nowhere yet. Brings up a confirmation dialog when the user selects the Quit menu item.
ListDialog.java How to Use BoxLayout Implements a modal dialog containing a scrolling list and two buttons.
PasswordDemo.java How to Use Threads Uses a dialog to prompt the user for a password. [PENDING: check]
TableDemo.java 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.
[PENDING: Bingo? Other demos?]


Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Using Swing Components