Java Reference
In-Depth Information
You have doubtlessly seen dialog boxes like the one shown in Figure 10.4. When your
system crashes, a dialog box opens and breaks the bad news. When you delete files, a
dialog box might pop up to make sure that you really want to do that.
These windows are an effective way to communicate with a user without the overhead of
creating a new class to represent the window, adding components to it, and writing event-
handling methods to take input. All these things are handled automatically when one of
the standard dialog boxes offered by
JOptionPane
is used.
The four standard dialog boxes are as follows:
ConfirmDialog
—Asks a question, with buttons for Yes, No, and Cancel responses
n
InputDialog
—Prompts for text input
n
MessageDialog
—Displays a message
n
OptionDialog
—Comprises all three of the other dialog box types
n
Each of these dialog boxes has its own show method in the
JOptionPane
class.
If you are setting up a look and feel to use with any of these dialog boxes, it must be
established before you open the box.
Confirm Dialog Boxes
The easiest way to create a Yes/No/Cancel dialog box is by calling the
showConfirmDialog(
Component
,
Object
)
method. The
Component
argument specifies
the container that should be considered to be the parent of the dialog box, and this infor-
mation is used to determine where the dialog window should be displayed. If
null
is
used instead of a container, or if the container is not a
JFrame
object, the dialog box will
be centered onscreen.
The second argument,
Object
, can be a string, a component, or an
Icon
object. If it's a
string, that text will be displayed in the dialog box. If it's a component or an
Icon
, that
object will be displayed in place of a text message.
This method returns one of three possible integer values, each a class constant of
JOptionPane
:
YES_OPTION
,
NO_OPTION
, and
CANCEL_OPTION
.
The following example uses a confirm dialog box with a text message and stores the
response in the
response
variable:
int response = JOptionPane.showConfirmDialog(null,
“Should I delete all of your irreplaceable personal files?”);
Figure 10.5 shows this dialog box.