The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
< Day Day Up > |
Several classes support dialogs windows that are more limited than frames . To create simple, standard dialogs, you use the JOptionPane class. [31] The ProgressMonitor class can put up a dialog that shows the progress of an operation. [32] Two other classes, JColorChooser and JFileChooser , also supply standard dialogs. [33] To bring up a print dialog, you use the Printing API. [34] To create custom dialogs, use the JDialog [35] class directly. [31] JOptionPane API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JOptionPane.html. [32] See How to Use Progress Bars (page 300). [33] See How to Use Color Choosers (page 167) and How to Use File Choosers (page 206). [34] You can learn more about printing in the "2D" trail in The Java Tutorial on this book's CD and online at: http://java.sun.com/docs/books/tutorial/2d. [35] JDialog API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JDialog.html. The code for simple dialogs can be minimal. Figure 11, for example, shows an informational dialog. Figure 11. A simple dialog.
Here's the code that creates and shows the dialog: JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green."); An Overview of Dialogs
Every dialog is dependent on a frame. When the frame is destroyed , so are its dialogs. When the frame is iconified , its dialogs disappear from the screen. When the frame is deiconified, its dialogs return to the screen. The AWT automatically provides this behavior. A dialog can be modal . When a modal dialog is visible, it blocks user input to all other windows in the program. The dialogs that JOptionPane provides are modal. To create a nonmodal dialog, you must use the JDialog class directly. The JDialog class is a subclass of the AWT java.awt.Dialog class. It adds to Dialog a root pane and support for a default close operation. These are the same features that JFrame has, and using JDialog directly is very similar to using JFrame directly. If you're going to use JDialog directly, then you should understand the material in Using Top-Level Containers (page 46) in Chapter 3 and How to Make Frames (Main Windows) (page 236) later in this chapter, especially Responding to Window-Closing Events (page 240). Even when you use JOptionPane to implement a dialog, you're still using a JDialog behind the scenes. The reason is that JOptionPane is simply a container that can automatically create a JDialog and add itself to the JDialog 's content pane. The DialogDemo Example
Figure 12 is a picture of an application that displays dialogs. Figure 12. The DialogDemo application.
Try This:
JOptionPane Features
Using JOptionPane , you can create and customize several different kinds of dialogs. JOptionPane provides support for laying out standard dialogs, providing icons, specifying the dialog's title and text, and customizing the button text. Other features allow you to customize the components the dialog displays and specify where the dialog should appear onscreen. You can even specify that an option pane put itself into an internal frame ( JInternalFrame ) instead of a JDialog .
Note: The internal frames that JOptionPane creates currently behave differently from modal dialogs. They don't behave modally and in general seem more like frames than like dialogs. For this reason, we don't currently recommend their use.
When you create a JOptionPane , look-and-feel-specific code adds components to it and determines their layout. JOptionPane 's icon support lets you easily specify which icon the dialog displays. You can use a custom icon, no icon at all, or any one of four standard JOptionPane icons (question, information, warning, and error). Each look and feel has its own versions of the four standard icons. Figure 13 shows the icons used in the Java look and feel. Figure 13. Icons provided by JOptionPane (Java look and feel shown).
Creating and Showing Simple Dialogs
Most simple modal dialogs you create and show using one of JOptionPane 's show Xxx- Dialog methods . If your dialog should be an internal frame, add Internal after show for example, showMessageDialog changes to showInternalMessageDialog . If you need to control the dialog's window-closing behavior or if the dialog isn't modal, you should directly instantiate JOptionPane and add it to a JDialog instance. Then invoke setVisible(true) on the JDialog to make it appear. The two most useful show Xxx Dialog methods are showMessageDialog and showOption-Dialog . The showMessageDialog method displays a simple, one-button dialog. The show-OptionDialog method displays a customized dialog that can display a variety of buttons with customized button text and can contain a standard text message or a collection of components. The other two show Xxx Dialog methods are used less often. The showConfirmDialog method asks the user to confirm something, but has the disadvantage of having standard button text (Yes/No or the localized equivalent, for example) rather than button text customized to the user's situation (Start/Cancel, for example). A fourth method, showInputDialog , is designed to display a modal dialog that gets a string from the user, using either a text field or an uneditable combo box. The following are some examples, taken from DialogDemo.java , of using showMessageDialog , showOptionDialog , and the JOptionPane constructor. For more example code, see DialogDemo.java and the other programs listed in Examples That Use Dialogs (page 199) later in this chapter. showMessageDialog
Displays a modal dialog with one button, which is labeled OK (or the localized equivalent). You can easily specify the message, icon, and title the dialog displays. Table 12 shows some examples. Table 12. Examples Using showMessageDialog
showOptionDialog
Displays a modal dialog with the specified buttons, icons, message, title, and so on. With this method, you can change the text that appears on the buttons of standard dialogs and perform many other kinds of customization. (See Table 13.) Table 13. An Example Using showOptionDialog
JOptionPane (constructor)
Creates a JOptionPane with the specified buttons, icons, message, title, and so on. You then have to add the option pane to a JDialog , register a property-change listener on the option pane, and show the dialog. (See Table 14.) See Stopping Automatic Dialog Closing (page 195) for details. Table 14. An Example Using JOptionPane
The arguments to all of the show Xxx Dialog methods and JOptionPane constructors are standardized, though the number of arguments for each method and constructor varies. The following list describes each argument. To look at the complete list of arguments for a particular method, see The Dialog API (page 196). Component parentComponent
Always the first argument to each show Xxx Dialog method, it must be a frame, a component inside a frame, or null. If you specify a frame, the dialog will appear over its center and depend on it. If you specify a component inside a frame, the dialog will appear over the center of that component and depend on that component's frame. If you specify null, the look and feel picks an appropriate position for the dialog generally the center of the screenand the dialog doesn't depend on any visible frame. The JOptionPane constructors don't include this argument. Instead, you specify the parent frame when you create the JDialog that contains the JOptionPane and use the JDialog setLocationRelativeTo method to set the dialog's position. Object message
A required argument, this specifies what the dialog should display in its main area. Generally, you specify a string, which results in the dialog displaying a label with the specified text. You can split the message over several lines by putting newline ( \n ) characters inside the message string. For example: "Complete the sentence:\n \"Green eggs and...\"" String title
Specifies the title of the dialog. int optionType
Specifies the buttons that appear at the bottom of the dialog. Choose from one of the following standard sets: DEFAULT_OPTION , YES_NO_OPTION , YES_NO_CANCEL_OPTION , OK_CANCEL_OPTION . int messageType
Determines the icon displayed in the dialog. Choose from the following values: PLAIN_MESSAGE (no icon), ERROR_MESSAGE , INFORMATION_MESSAGE , WARNING_MESSAGE , QUESTION_MESSAGE . Icon icon
The icon to display in the dialog. Object[] options
Further specifies the option buttons to appear at the bottom of the dialog. Generally, you specify an array of strings for the buttons. See Customizing Button Text (page 194) for more information. Object initialValue
Specifies the default value to be selected. You can either let the default icon be used or specify the icon using the message type or icon argument. By default, a dialog created with showMessageDialog displays the information icon, and a dialog created with showConfirmDialog or showInputDialog displays the question icon. An option pane created with a JOptionPane constructor displays no icon by default. To specify that the dialog display a standard icon or no icon, specify the message type. To specify a custom icon, use the icon argument. The icon argument takes precedence over the message type; as long as the icon argument has a non-null value, the dialog displays the specified icon. Customizing Button Text
When you use JOptionPane to create a dialog, you can choose either to use the standard button text (which might vary by look and feel) or to specify different text. The code shown in Table 15, taken from DialogDemo.java , creates two Yes/No dialogs. The first is implemented with showConfirmDialog , which uses the look-and-feel wording for the two buttons. The second uses showOptionDialog so that it can customize the wording. With the exception of wording changes, the dialogs are identical. Table 15. Two Yes/No Dialog Examples
Getting the User's Input from a Dialog
As the previous code snippets in Table 15 show, the showMessageDialog , showConfirm-Dialog , and showOptionDialog methods return an integer indicating the user's choice. The values for this integer are YES_OPTION , NO_OPTION , CANCEL_OPTION , OK_OPTION , and CLOSED_OPTION . Except for CLOSED_OPTION , each option corresponds to the button the user presses. CLOSED_OPTION indicates that the user is closing the dialog window explicitly rather than by choosing a button inside the option pane. Even if you change the strings that the standard dialog buttons display, the return value is still one of the predefined integers. For example, a YES_NO_OPTION dialog always returns one of the following values: YES_OPTION , NO_OPTION , or CLOSED_OPTION . If you're designing a custom dialog, on the other hand, you need to design its API so that you can query the dialog about what the user chose. For example, the dialog implemented in CustomDialog.java [37] has a getValidatedText method that returns the text the user entered. [37] You can find CustomDialog.java here: JavaTutorial/uiswing/components/example-1dot4/CustomDialog.java . Stopping Automatic Dialog Closing
By default, when the user clicks a JOptionPane -created button, the dialog closes . But what if you want to check the user's answer before closing the dialog? In this case, you must implement your own property-change listener so that when the user clicks a button the dialog doesn't automatically close. DialogDemo contains two dialogs that implement a property-change listener. One of these is a custom modal dialog, implemented in CustomDialog , 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 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 JDialog 's set-DefaultCloseOperation 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, ignore the bold 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.setVisible(true); 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
Tables 16 through 18 list the commonly used JOptionPane [38] and JDialog [39] constructors and methods. Other methods you're likely to call are defined by the Dialog , Window , and Component classes and include pack , setSize , and setVisible . [38] JOptionPane API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JOptionPane.html. [39] JDialog API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JDialog.html. Table 16. Showing Standard Modal Dialogs (Using JOptionPane Class Methods)
Table 17. Methods for Using JOptionPanes Directly
Table 18. Frequently Used JDialog Constructors and Methods
Examples That Use Dialogs
The following table lists examples that use JOptionPane or JDialog . To find other examples that use dialogs, see these sections: Examples That Monitor Progress (page 310), Examples That Use Color Choosers (page 175), and Examples That Use File Choosers (page 220).
|
< Day Day Up > |