Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages

How to Make Dialogs

Swing provides support for dialogs -- windows that are more limited than frames -- with the JOptionPane(in the API reference documentation) and JDialog(in the API reference documentation) classes. Another class, JFileChooser, will soon become a supported part of Swing. You can read about JFileChooser in The Swing 1.0.2 File Chooser, an article in The Swing Connection.

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(null, "Eggs aren't supposed to be green.");
The rest of this section covers the following topics:

Dialog Features

A dialog is, by convention, 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. A modal dialog blocks its program's UI until the dialog is dismissed. All the dialogs that JOptionPane provides are modal. To create a non-modal dialog, you must use the JDialog class directly. You can also use JDialog to implement custom modal dialogs that don't require the layout and icon support that JOptionPane provides.

JOptionPane lets you use your own icon or any one of four standard dialog icons (question, information, warning, error). Each look and feel has its own versions of the four standard icons. Here are the icons used in the default look and feel (the Java Look and Feel, nicknamed Metal):

The Metal icon for dialogs that ask questionsThe Metal icon for informational dialogsThe Metal icon for warning dialogs The Metal icon for error dialogs

The first argument to any JOptionPane showXxxDialog method specifies the component over which the dialog should be centered. The frame that contains this component is the one that the dialog depends on. If you specify null, then the dialog is independent, and it appears in the middle of the screen.

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

A yes/no dialog
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 example, taken from DialogDemo.java, creates two Yes/No dialogs. The first dialog, shown above, 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.

...//create the yes/no dialog:
int n = JOptionPane.showConfirmDialog(
	null, "Do 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!");
}

...//create the yes/no (but in other words) dialog:
String string1 = "Yes, I like them";
String string2 = "No, they're disgusting!";
Object[] options = {string1, string2};
int n = JOptionPane.showOptionDialog(null,
		"Do you like green eggs and ham?",
		"A Silly Question",
		JOptionPane.YES_NO_OPTION,
		JOptionPane.QUESTION_MESSAGE,
		null,
		options,
		string1);
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 Modal Dialog

As the previous example showed, the JOptionPane showXxxDialog methods return a value. For the simple, standard JOptionPane dialogs, the value returned is YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, or 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. [PENDING: check]

[PENDING: continue input discussion]

Stopping Automatic Dialog Dismissal

By default, when the user clicks a button or explicitly closes the 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?]. [Link to JComponent and Component discussions.]

The API is listed as follows:

Frequently Used JOptionPane Methods
Method Purpose
int getMaxCharactersPerLineCount() By default, returns Integer.MAX_VALUE. Override this in a JOptionPane subclass to make the option pane break lines so that they have no more than the specified number of characters.

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

[PENDING: put table of examples here]
[PENDING: somewhere say that JOptionPane is just a container and JDialog has a content pane.]


Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages