Dialog Boxes Core Java

So far, all our user interface components have appeared inside a frame window that was created in the application. This is the most common situation if you write applets that run inside a web browser. But if you write applications, you usually want separate dialog boxes to pop up to give information to or get information from the user.

Just as with most windowing systems, AWT distinguishes between modal and modeless dialog boxes. A modal dialog box won’t let users interact with the remaining windows of the application until he or she deals with it. You use a modal dialog box when you need information from the user before you can proceed with execution. For example, when the user wants to read a file, a modal file dialog box is the one to pop up. The user must specify a file name before the program can begin the read operation. Only when the user closes the (modal) dialog box can the application proceed.

A modeless dialog box lets the user enter information in both the dialog box and the remainder of the application. One example of a modeless dialog is a toolbar. The toolbar can stay in place as long as needed, and the user can interact with both the application window and the toolbar as needed.

We start this section with the simplest dialogs—modal dialogs with just a single message. Swing has a convenient JOptionPane class that lets you put up a simple dialog without writing any special dialog box code. Next, you see how to write more complex dialogs by implementing your own dialog windows. Finally, you see how to transfer data from your application into a dialog and back. We conclude this section by looking at two standard dialogs: file dialogs and color dialogs.

File dialogs are complex, and you definitely want to be familiar with the Swing JFileChooser for this purpose—it would be a real challenge to write your own. The JColorChooser dialog is useful when you want users to pick colors.

Option Dialogs

Swing has a set of ready-made simple dialogs that suffice when you need to ask the user for a single piece of information. The JOptionPane has four static methods to show these simple dialogs:

Figure below shows a typical dialog. As you can see, the dialog has the following components:

  • An icon
  • A message
  • One or more option buttons

An option dialog

An option dialog

The input dialog has an additional component for user input. This can be a text field into which the user can type an arbitrary string, or a combo box from which the user can select one item.

The exact layout of these dialogs, and the choice of icons for standard message types, depend on the pluggable look and feel.

The icon on the left side depends on one of five message types:

The PLAIN_MESSAGE type has no icon. Each dialog type also has a method that lets you supply your own icon instead. For each dialog type, you can specify a message. This message can be a string, an icon, a user interface component, or any other object. Here is how the message object is displayed:

You can see these options by running the program in Listing below Of course, supplying a message string is by far the most common case. Supplying a Component gives you ultimate flexibility because you can make the paint Component method draw anything you want.

The buttons on the bottom depend on the dialog type and the option type. When calling showMessageDialog and show Input Dialog, you get only a standard set of buttons (OK and OK/ Cancel, respectively). When calling showConfirmDialog, you can choose among four option types:

With the showOptionDialog you can specify an arbitrary set of options. You supply an array of objects for the options. Each array element is rendered as follows:

Any other object Apply toString and make a button with the resulting string as label The return values of these functions are as follows:

The showConfirmDialog and showOptionDialog return integers to indicate which button the user chose. For the option dialog, this is simply the index of the chosen option or the value CLOSED_OPTION if the user closed the dialog instead of choosing an option. For the confirmation dialog, the return value can be one of the following:

This all sounds like a bewildering set of choices, but in practice it is simple. Follow these steps:

  1. Choose the dialog type (message, confirmation, option, or input).
  2. Choose the icon (error, information, warning, question, none, or custom).
  3. Choose the message (string, icon, custom component, or a stack of them).
  4. For a confirmation dialog, choose the option type (default, Yes/No, Yes/No/ Cancel, or OK/Cancel).
  5. For an option dialog, choose the options (strings, icons, or custom components) and the default option.
  6. For an input dialog, choose between a text field and a combo box.
  7. Locate the appropriate method to call in the JOptionPane API.

For example, suppose you want to show the dialog in Figure below. The dialog shows a message and asks the user to confirm or cancel. Thus, it is a confirmation dialog. The icon is a question icon. The message is a string. The option type is OK _CANCEL _OPTION. Here is the call you would make:

The OptionDialogTest program

The OptionDialogTest program

javax.swing.JOptionPane 1.2

  • static void showMessageDialog(Component parent, Object message, String title, int messageType,Icon icon)
  • static void showMessageDialog(Component parent, Object message, String title, int messageType)
  • static void showMessageDialog(Component parent, Object message)
  • static void showInternalMessageDialog(Component parent, Object message, String title,
  • int messageType, Icon icon)
  • static void showInternalMessageDialog(Component parent, Object message, String title, int messageType)
  • static void showInternalMessageDialog(Component parent, Object message)
    shows a message dialog or an internal message dialog. (An internal dialog is rendered entirely within its owner frame.)
  • static int showConfirmDialog(Component parent, Object message, String title, int optionType,
    int messageType, Icon icon)
  • static int showConfirmDialog(Component parent, Object message, String title, int optionType,
    int messageType)

javax.swing.JOptionPane

static int showConfirmDialog(Component parent, Object message, String title, int optionType)

  • static int showConfirmDialog(Component parent, Object message)
  • static int showInternalConfirmDialog(Component parent, Object message, String title, int optionType, int messageType, Icon icon)
  • static int showInternalConfirmDialog(Component parent, Object message, String title, int optionType, int messageType)
  • static int showInternalConfirmDialog(Component parent, Object message, String title, int optionType)
  • static int showInternalConfirmDialog(Component parent, Object message)

shows a confirmation dialog or an internal confirmation dialog. (An internal dialog is rendered entirely within its owner frame.) Returns the option selected by the user (one of OK _OPTION, CANCEL _OPTION, YES _OPTION, NO _OPTION), or CLOSED_OPTION if the user closed the dialog.

  • static int showOptionDialog(Component parent, Object message, String title, int optionType,
  • int messageType, Icon icon, Object[] options, Object default)
  • static int showInternalOptionDialog(Component parent, Object message, String title,

int optionType, int messageType, Icon icon, Object[] options, Object default) shows an option dialog or an internal option dialog. (An internal dialog is rendered entirely within its owner frame.) Returns the index of the option selected by the user, or CLOSED_OPTION if the user canceled the dialog.

icon An icon to show instead of one of the standard icons options An array of options (can be strings, icons, or components) default The default option to present to the user

static Object show Input Dialog (Component parent, Object message, String title, int message- Type, Icon icon, Object[] values, Object default)

  • static String showInputDialog(Component parent, Object message, String title, int message-
    Type)
  • static String showInputDialog(Component parent, Object message)
  • static String showInputDialog(Object message)
  • static String showInputDialog(Component parent, Object message, Object default)
  • static String showInputDialog(Object message, Object default)
  • static Object showInternalInputDialog(Component parent, Object message, String title,
  • int messageType, Icon icon, Object[] values, Object default)

  • static String showInternalInputDialog(Component parent, Object message, String title, int messageType)
  • static String showInternalInputDialog(Component parent, Object message) shows an input dialog or an internal input dialog. (An internal dialog is rendered entirely within its owner frame.) Returns the input string typed by the user, or null if the user canceled the dialog.

Creating Dialogs

In the last section, you saw how to use the JOptionPane class to show a simple dialog. In this section, you see how to create such a dialog by hand.

a typical modal dialog box, a program information box that is displayed when the user clicks the About button.

To implement a dialog box, you extend the JDialog class. This is essentially the same process as extending JFrame for the main window for an application. More precisely:

  1. In the constructor of your dialog box, call the constructor of the superclass JDialog.
  2. Add the user interface components of the dialog box.
  3. Add the event handlers.
  4. Set the size for the dialog box.

When you call the superclass constructor, you will need to supply the owner frame, the title of the dialog, and the modality.
The owner frame controls where the dialog is displayed. You can supply null as the owner; then, the dialog is owned by a hidden frame.

The modality specifies which other windows of your application are blocked while the dialog is displayed. A modeless dialog does not block other windows. A modal dialog blocks all other windows of the application (except children of the dialog). You would use a modeless dialog for a toolbox that the user can always access. On the other hand, you would use a modal dialog if you want to force the user to supply required information before continuing.

An About dialog box

An About dialog box

Here’s the code for a dialog box:

As you can see, the constructor adds user interface elements: in this case, labels and a button. It adds a handler to the button and sets the size of the dialog. To display the dialog box, you create a new dialog object and make it visible:

Actually, in the sample code below, we create the dialog box only once, and we can reuse it whenever the user clicks the About button.

When the user clicks the Ok button, the dialog box should close. This is handled in the event handler of the Ok button:

When the user closes the dialog by clicking on the Close box, then the dialog is also hidden. Just as with a JFrame, you can override this behavior with the setDefaultCloseOperation method.

javax.swing.JDialog 1.2

  • public JDialog(Frame parent, String title, boolean modal)
    constructs a dialog. The dialog is not visible until it is explicitly shown.

Data Exchange

The most common reason to put up a dialog box is to get information from the user. You have already seen how easy it is to make a dialog box object: Give it initial data and then call setVisible(true) to display the dialog box on the screen. Now let us see how to transfer data in and out of a dialog box.

Consider the dialog box that could be used to obtain a user name and a password to connect to some on-line service.

Password dialog box

Password dialog box

Your dialog box should provide methods to set default data. For example, the Password- Chooser class of the example program has a method, setUser, to place default values into the next fields:

Once you set the defaults (if desired), you show the dialog by calling setVisible(true). The dialog is now displayed. The user then fills in the information and clicks the Ok or Cancel button. The event handlers for both buttons call setVisible(false), which terminates the call to setVisible(true). Alternatively, the user may close the dialog. If you did not install a window listener for the dialog, then the default window closing operation applies: The dialog becomes invisible, which also terminates the call to setVisible(true).

The important issue is that the call to setVisible(true) blocks until the user has dismissed the dialog. This makes it easy to implement modal dialogs You want to know whether the user has accepted or canceled the dialog. Our samplecode sets the ok flag to false before showing the dialog. Only the event handler for theOk button sets the ok flag to true. In that case, you can retrieve the user input from thedialog.

The example program contains another useful improvement. When you construct a JDialog object, you need to specify the owner frame. However, quite often you want to show the same dialog with different owner frames. It is better to pick the owner frame when you are ready to show the dialog, not when you construct the PasswordChooser object. The trick is to have the PasswordChooser extend JPanel instead of JDialog. Build a JDialog object on the fly in the showDialog method:

Note that it is safe to have owner equal to null. You can do even better. Sometimes, the owner frame isn’t readily available. It is easy enough to compute it from any parent component, like this:

We use this enhancement in our sample program. The JOptionPane class also uses this mechanism. Many dialogs have a default button, which is automatically selected if the user presses a trigger key ( ENTER in most “look and feel” implementations). The default button is specially marked, often with a thick outline.

You set the default button in the root pane of the dialog: dialog.getRootPane().setDefaultButton(okButton

If you follow our suggestion of laying out the dialog in a panel, then you must be careful to set the default button only after you wrapped the panel into a dialog. The panel itself has no root pane.

javax.swing.SwingUtilities 1.2

  • Container getAncestorOfClass(Class c, Component comp) returns the innermost parent container of the given component that belongs to the given class or one of its subclasses.
  • JRootPane getRootPane()
    gets the root pane enclosing this component, or null if this component does not have an ancestor with a root pane.
  • void setDefaultButton(JButton button)
    sets the default button for this root pane. To deactivate the default button, call this method with a null parameter.
  • boolean isDefaultButton()
    returns true if this button is the default button of its root pane.

File Dialogs

When you write an application, you often want to be able to open and save files. A good file dialog box that shows files and directories and lets the user navigate the file system is hard to write, and you defnitely don’t want to reinvent that wheel. Fortunately, Swing provides a JFileChooser class that allows you to display a file dialog box similar to the one that most native applications use. JFileChooser dialogs are always modal. Note that the JFileChooser class is not a subclass of JDialog. Instead of calling set- Visible(true), you call showOpenDialog to display a dialog for opening a file or you call show Save Dialog to display a dialog for saving a file. The button for accepting a file is then automatically labeled Open or Save. You can also supply your own button label with the showDialog method. example of the file chooser dialog box.

File chooser dialog box

File chooser dialog box

Here are the steps needed to put up a file dialog box and recover what the user chooses from the box:

  1. Make a JFileChooser object. Unlike the constructor for the JDialog class, you do not supply the parent component. This allows you to reuse a file chooser dialog with multiple frames.
  2. For example:
  3. Set the directory by calling the setCurrentDirectory method.
  4. For example, to use the current working directory

    you need to supply a File object. File objects. All you need to know for now is that the constructor File(String filename) turns a file or directory name into a File object.

  5. If you have a default file name that you expect the user to choose, supply it with the set Selected File method:
  6. To enable the user to select multiple files in the dialog, call the setMultiSelectionEnabled method. This is, of course, entirely optional and not all that common.
  7. If you want to restrict the display of files in the dialog to those of a particular type (for example, all files with extension .gif), then you need to set a file filter. We discuss file filters later in this section.
  8. By default, a user can select only files with a file chooser. If you want the user to select directories, use the setFileSelectionMode method. Call it with JFile Chooser .FILES _ONLY (the default), JFil eChooser .DIRECTORIES _ONLY, or JFile Chooser.FILES _AND _DIRECTORIES.
  9. Show the dialog box by calling the show Open Dialog or show Save Dialog method. You must supply the parent component in these calls:
  10. The only difference between these calls is the label of the “approve button,” the button that the user clicks to finish the file selection. You can also call the showDialog method and pass an explicit text for the approve button:

    These calls return only when the user has approved, canceled, or dismissed the file dialog. The return value is JFile Chooser .APPROVE _OPTION, JFile Chooser .CANCEL _OPTION, or File Chooser .ERROR _OPTION

  11. You get the selected file or files with the getSelectedFile() or getSelectedFiles() method.
    These methods return either a single File object or an array of File objects. If you just need the name of the file object, call its getPath method. For example:

For the most part, these steps are simple. The major difficulty with using a file dialog is to specify a subset of files from which the user should choose. For example, suppose the user should choose a GIF image file. Then, the file chooser should only display files with extension .gif. It should also give the user some kind of feedback that the displayed files are of a particular category, such as “GIF Images.” But the situation can be more complex. If the user should choose a JPEG image file, then the extension can be either .jpg or .jpeg. Rather than coming up with a mechanism to codify these complexities, the designers of the file chooser supply a more elegant mechanism: to restrict the displayed files, you supply an object that extends the abstract class javax.swing.filechooser.FileFilter. The file chooser passes each file to the file filter and displays only the files that the file filter accepts.

At the time of this writing, two such subclasses are supplied: the default filter that accepts all files, and a filter that accepts all files with a given extension. Moreover, it is easy to write ad hoc file filters. You simply implement the two abstract methods of the FileFilter superclass:

The first method tests whether a file should be accepted. The second method returns a description of the file type that can be displayed in the file chooser dialog. Once you have a file filter object, you use the setFileFilter method of the JFileChooser class to install it into the file chooser object:
chooser .set File Filter (new File Name Extension Filter("Image files", "gif", "jpg");

You can install multiple filters to the file chooser by calling


The user selects a filter from the combo box at the bottom of the file dialog. By default, the “All files” filter is always present in the combo box. This is a good idea, just in case a user of your program needs to select a file with a nonstandard extension. However, if you want to suppress the “All files” filter, call chooser .set Accept AllFile Filter Used(false)

Finally, you can customize the file chooser by providing special icons and file descriptions for each file that the file chooser displays. You do this by supplying an object of a class extending the FileView class in the javax.swing.filechooser package. This is definitely an advanced technique. Normally, you don't need to supply a file view—the pluggable look and feel supplies one for you. But if you want to show different icons for special file types, you can install your own file view. You need to extend the FileView class and implement five methods:

Then you use the setFileView method to install your file view into the file chooser.The file chooser calls your methods for each file or directory that it wants to display. If your method returns null for the icon, name, or description, the file chooser then consults the default file view of the look and feel. That is good, because it means you need to deal only with the file types for which you want to do something different. The file chooser calls the isTraversable method to decide whether to open a directory when a user clicks on it. Note that this method returns a Boolean object, not a Boolean value! This seems weird, but it is actually convenient—if you aren't interested in deviating from the default file view, just return null. The file chooser will then consult the default file view. In other words, the method returns a Boolean to let you choose among three options: true (Boolean.TRUE), false (Boolean.FALSE), and don't care (null). The example program contains a simple file view class. That class shows a particular icon whenever a file matches a file filter. We use it to display a palette icon for all image files.
class FileIconView extends FileView

all this file view into your file chooser with the setFileView method:

The file chooser will then show the palette icon next to all files that pass the filter and use the default file view to show all other files. Naturally, we use the same filter that we set in the file chooser.

Finally, you can customize a file dialog by adding an accessory component. For example, Figure below shows a preview accessory next to the file list. This accessory displays a thumbnail view of the currently selected file.

A file dialog with a preview accessory

A file dialog with a preview accessory

An accessory can be any Swing component. In our case, we extend the JLabel class and set its icon to a scaled copy of the graphics image:

There is just one challenge. We want to update the preview image whenever the user selects a different file. The file chooser uses the “JavaBeans” mechanism of notifying interested listeners whenever one of its properties changes. The selected file is a property that you can monitor by installing a Property Change Listener. Here is the code that you need to trap the notifications:

In our example program, we add this code to the ImagePreviewer constructor. Listing below contains a modification of the ImageViewer program in which the file chooser has been enhanced by a custom file view and a preview accessory.

javax.swing.JFileChooser 1.2

  • JFileChooser() creates a file chooser dialog box that can be used for multiple frames.
  • void setCurrentDirectory(File dir)
    sets the initial directory for the file dialog box.
  • void setSelectedFile(File file)
    void setSelectedFiles(File[] file)sets the default file choice for the file dialog box.
  • void setMultiSelectionEnabled(boolean b)
    sets or clears multiple selection mode.
  • void setFileSelectionMode(int mode)
    lets the user select files only (the default), directories only, or both files and directories. The mode parameter is one of JFile Chooser .FILES _ONLY,JFile Chooser .DIRECTORIES _ONLY, and JFile Chooser .FILES _AND _DIRECTORIES.
  • int showOpenDialog(Component parent)
  • int showSaveDialog(Component parent)
  • int showDialog(Component parent, String approveButtonText)
    shows a dialog in which the approve button is labeled “Open”, “Save”, or with the approveButtonText string. Returns APPROVE _OPTION, CANCEL_OPTION (if the user selected the cancel button or dismissed the dialog), or ERROR_OPTION (if an error occurred).
  • File getSelectedFile()
  • File[] getSelectedFiles()
    gets the file or files that the user selected (or returns null if the user didn’t select any file).
  • void setFileFilter(FileFilter filter)
    sets the file mask for the file dialog box. All files for which filter.accept returns true will be displayed. Also adds the filter to the list of choosable filters.
  • void add Choosable File Filter(File Filter filter)
    adds a file filter to the list of choosable filters.
  • void setAcceptAllFileFilterUsed(boolean b)
    includes or suppresses an “All files” filter in the filter combo box.
  • void resetChoosableFileFilters()
    clears the list of choosable filters. Only the “All files” filter remains unless it is explicitly suppressed.
  • void setFileView(FileView view)
    sets a file view to provide information about the files that the file chooser displays.
  • void setAccessory(JComponent component)
    sets an accessory component.
  • boolean accept(File f)
    returns true if the file chooser should display this file.
  • String getDescription()
    returns a description of this file filter, for example, "Image files (*.gif,*.jpeg)".
  • FileNameExtensionFilter(String description, String ... extensions)
    constructs a file filter with the given descriptions that accepts all directories and all files whose names end in a period followed by one of the given extension strings.
  • String getName(File f)
    returns the name of the file f, or null. Normally, this method simply returns f.getName().
  • String getDescription(File f)
    returns a humanly readable description of the file f, or null. For example, if f is an HTML document, this method might return its title.
  • String getTypeDescription(File f)
    returns a humanly readable description of the type of the file f, or null. For example, if f is an HTML document, this method might return a string "Hypertext document
  • Icon getIcon(File f)
    returns an icon for the file f, or null. For example, if f is a JPEG file, this method might return a thumbnail icon.
  • Boolean isTraversable(File f)
    returns Boolean.TRUE if f is a directory that the user can open. This method might return false if a directory is conceptually a compound document. Like all FileView methods, this method can return null to signify that the file chooser should consult the default view instead.

Color Choosers

As you saw in the preceding section, a high-quality file chooser is an intricate user interface component that you definitely do not want to implement yourself. Many user interface toolkits provide other common dialogs: to choose a date/time, currency value, font, color, and so on. The benefit is twofold. Programmers can simply use a high-quality implementation rather than rolling their own. And users have a common experience for these selections.

At this point, Swing provides only one additional chooser, the JColorChooser. You use it to let users pick a color value. Like the JFileChooser class, the color chooser is a component, not a dialog, but it contains convenience methods to create dialogs that contain a color chooser component.

Here is how you show a modal dialog with a color chooser:

Alternatively, you can display a modeless color chooser dialog. You supply the following:

  • A parent component
  • The title of the dialog
  • A flag to select either a modal or a modeless dialog
  • A color chooser
  • Listeners for the “OK” and “Cancel” buttons (or null if you don’t want a listener)

The Swatches pane of a color chooser

The Swatches pane of a color chooser

The HSB pane of a color chooser

The HSB pane of a color chooser

The RGB pane of a color chooser

The RGB pane of a color chooser

Here is how you make a modeless dialog that sets the background color when the user clicks the OK button:

You can do even better than that and give the user immediate feedback of the color selection. To monitor the color selections, you need to obtain the selection model of the chooser and add a change listener:

In this case, there is no benefit to the OK and Cancel buttons that the color chooser dialog provides. You can just add the color chooser component directly into a modeless dialog:

javax.swing.JColorChooser 1.2

  • JColorChooser()
    constructs a color chooser with an initial color of white.
  • Color getColor()
  • void setColor(Color c)
    gets and sets the current color of this color chooser.
  • static Color showDialog(Component parent, String title, Color initialColor)
    shows a modal dialog that contains a color chooser.
  • static JDialog createDialog(Component parent, String title, boolean modal, JColorChooser
    chooser, Action Listener okListener, Action Listener cancel Listener) creates a dialog box that contains a color chooser.

This ends our discussion of user interface components


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics