Java Reference
In-Depth Information
Dialogs: When Later Just Won't Do
Problem
You need a bit of feedback from the user
right now
.
Solution
Use a
JOptionPane
method to show a prebuilt dialog. Or subclass
JDialog
.
Discussion
It's fairly common to want to confirm an action with the user or to bring some problem to her
attention right away, rather than waiting for her to read a logfile that she might or might not
get around to. These pop-up windows are called dialogs. The
JOptionPane
class has a num-
ber of
show…Dialog()
methods that let you display several commonly used dialogs, includ-
ing those shown in
Figure 14-6
.
Figure 14-6. JOptionPane in action
The simplest form is
showMessageDialog()
, and its first argument is the owning
Frame
or
JFrame
. If you don't know it, pass null, but Java doesn't guarantee to give input focus back
to your main window when the dialog is dismissed. The second argument is the message
text, and the third is the title bar title. Last but not least is code telling which of several preb-
uilt bitmaps should be displayed. This program produces the “Coded Message” dialog in the
figure:
public
public class
class
JOptionDemo
JOptionDemo
extends
extends
JFrame
{