Using the JFC/Swing Packages |
Swing provides support for dialogs -- windows that are more limited than frames -- with theJOptionPane
andJDialog
classes. Another class,JFileChooser
, will soon become a supported part of Swing. You can read aboutJFileChooser
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:
The rest of this section covers the following topics:JOptionPane.showMessageDialog(null, "Eggs aren't supposed to be green.");
- Dialog features
- The DialogDemo example
- Customizing button text in a standard dialog
- Getting the user's input from a standard dialog
- Stopping automatic dialog dismissal
- The dialog API
- Examples that use dialogs
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 theJDialog
class directly. You can also useJDialog
to implement custom modal dialogs that don't require the layout and icon support thatJOptionPane
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 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 specifynull
, 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:
- Compile and run the application. The source file is
DialogDemo.java
.
See Getting Started with Swing if you need help.- 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.- Iconify the DialogDemo window while a dialog is showing.
The dialog will disappear from the screen until you deiconify the DialogDemo window.- 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 useJOptionPane
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 fromDialogDemo.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, theJOptionPane
showXxxDialog
methods return a value. For the simple, standardJOptionPane
dialogs, the value returned isYES_OPTION
,NO_OPTION
,CANCEL_OPTION
,OK_OPTION
, orCLOSED_OPTION
. Except forCLOSED_OPTION
, each option corresponds to the button the user pressed. WhenCLOSED_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 inCustomDialog.java
, that usesJOptionPane
both to get the standard icon and to get layout assistance. The other dialog, whose code is below, uses a standard Yes/NoJOptionPane
, 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
'ssetDefaultCloseOperation
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 usedJOptionPane
andJDialog
constructors and methods. Other methods you're likely to call are defined by theJComponent
andComponent
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 (lists some of the most useful of the manyJOptionPane
methods.- Frequently Used
JDialog
Methods
Frequently Used JOptionPane
MethodsMethod Purpose int getMaxCharactersPerLineCount()
By default, returns Integer.MAX_VALUE
. Override this in aJOptionPane
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 MethodsMethod/Constructor Purpose JDialog()
JDialog(Frame)
JDialog(Frame, boolean)
JDialog(Frame, String)
JDialog(Frame, String, boolean)Creates a JDialog
instance. TheFrame
argument, if any, is the frame (usually aJFrame
object) that the dialog depends on. Make the boolean argumenttrue
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.]
Using the JFC/Swing Packages |