Dialogs
A
dialog is another standard feature of user interfaces. Dialogs are
frequently used to present information to the user (“Your fruit
salad is ready.”) or to ask a question (“Shall I bring
the car around?”). Dialogs are used so commonly in GUI
applications that Swing includes a handy set of pre-built dialogs.
These are accessible from static methods in the JOptionPane
class. Many variations are possible;
JOptionPane groups them into four basic types:
- message dialog
Displays a message to the user, usually accompanied by an OK button.
- confirmation dialog
Ask a question and displays answer buttons, usually Yes, No, and Cancel.
- input dialog
Asks the user to type in a string.
- option dialogs
The most general type—you pass it your own components, which are displayed in the dialog.
A confirmation dialog is shown in Figure 14.10.

Figure 14-10. Using a confirmation dialog
Let’s look at examples of each kind of dialog. The following code produces a message dialog:
JOptionPane.showMessageDialog(f, "You have mail.");
The first parameter to showMessageDialog( )
is the parent component (in this
case f, an existing JFrame).
The dialog will be centered on the parent component. If you pass
null for the parent component, the dialog is
centered in your screen. The dialogs that
JOptionPane displays are
modal
, which means they block other input to
your application while they are showing.
Here’s a slightly ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access