Dialogs

A dialog is another standard feature of user interfaces. Dialogs are frequently used to present information to the user (“Your fruit salad is ready.”) or to ask a question (“Shall I bring the car around?”). Dialogs are used so commonly in GUI applications that Swing includes a handy set of pre-built dialogs. These are accessible from static methods in the JOptionPane class. Many variations are possible; JOptionPane groups them into four basic types:

message dialog

Displays a message to the user, usually accompanied by an OK button.

confirmation dialog

Ask a question and displays answer buttons, usually Yes, No, and Cancel.

input dialog

Asks the user to type in a string.

option dialogs

The most general type—you pass it your own components, which are displayed in the dialog.

A confirmation dialog is shown in Figure 14.10.

Using a confirmation dialog

Figure 14-10. Using a confirmation dialog

Let’s look at examples of each kind of dialog. The following code produces a message dialog:

JOptionPane.showMessageDialog(f, "You have mail.");

The first parameter to showMessageDialog( ) is the parent component (in this case f, an existing JFrame). The dialog will be centered on the parent component. If you pass null for the parent component, the dialog is centered in your screen. The dialogs that JOptionPane displays are modal , which means they block other input to your application while they are showing.

Here’s a slightly fancier message dialog. We’ve specified a title for the dialog and a message type, which affects the icon that is displayed:

JOptionPane.showMessageDialog(f, "You are low on memory.",
        "Apocalyptic message", JOptionPane.WARNING_MESSAGE);

Here’s how to display the confirmation dialog shown in Figure 14.10:

int result = JOptionPane.showConfirmDialog(null,
        "Do you want to remove Windows now?");

In this case, we’ve passed null for the parent component. Special values are returned from showConfirmDialog( ) to indicate which button was pressed. There’s a full example below that shows how to use this return value.

Sometimes you need to ask the user to type some input. The following code puts up a dialog requesting the user’s name:

String name = JOptionPane.showInputDialog(null,
        "Please enter your name.");

Whatever the user types is returned as a String, or null if the user presses the Cancel button.

The most general type of dialog is the option dialog. You supply an array of objects that you wish to be displayed; JOptionPane takes care of formatting them and displaying the dialog. The following example displays a text label, a JTextField, and a JPasswordField. (Text components are described in the next chapter.)

JTextField userField = new JTextField( );
JPasswordField passField = new JPasswordField( );
String message = "Please enter your user name and password.";
result = JOptionPane.showOptionDialog(f,
    new Object[] { message, userField, passField },
    "Login", JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null, null, null);

We’ve also specified a dialog title (“Login”) in the call to showOptionDialog( ). We want OK and Cancel buttons, so we pass OK_CANCEL_OPTION as the dialog type. The QUESTION_MESSAGE argument indicates we’d like to see the question mark icon. The last three items are optional: an Icon, an array of different choices, and a current selection. Since the icon parameter is null, a default is used. If the array of choices and the current selection parameters were not null, JOptionPane might try to display the choices in a list or combo box.

The following application includes all the examples we’ve covered:

import javax.swing.*;

public class ExerciseOptions {
  public static void main(String[] args) {
    JFrame f = new JFrame("ExerciseOptions v1.0");
    f.setSize(200, 200);
    f.setLocation(200, 200);
    f.setVisible(true);
    
    JOptionPane.showMessageDialog(f, "You have mail.");
    JOptionPane.showMessageDialog(f, "You are low on memory.",
        "Apocalyptic message", JOptionPane.WARNING_MESSAGE);
    
    int result = JOptionPane.showConfirmDialog(null,
        "Do you want to remove Windows now?");
    switch (result) {
      case JOptionPane.YES_OPTION:
        System.out.println("Yes"); break;
      case JOptionPane.NO_OPTION:
        System.out.println("No"); break;
      case JOptionPane.CANCEL_OPTION:
        System.out.println("Cancel"); break;
      case JOptionPane.CLOSED_OPTION:
        System.out.println("Closed"); break;
    }
    
    String name = JOptionPane.showInputDialog(null,
        "Please enter your name.");
    System.out.println(name);
    
    JTextField userField = new JTextField( );
    JPasswordField passField = new JPasswordField( );
    String message = "Please enter your user name and password.";
    result = JOptionPane.showOptionDialog(f,
        new Object[] { message, userField, passField },
        "Login", JOptionPane.OK_CANCEL_OPTION,
        JOptionPane.QUESTION_MESSAGE,
        null, null, null);
    if (result == JOptionPane.OK_OPTION)
      System.out.println(userField.getText( ) +
          " " +  new String(passField.getPassword( )));
    
    System.exit(0);
  }
}

File Selection Dialog

A JFileChooser is a standard file-selection box. As with other Swing components, JFileChooser is implemented in pure Java, so it looks and acts the same on different platforms.

Selecting files all day can be pretty boring without a greater purpose, so we’ll exercise the JFileChooser in a mini-editor application. Editor provides a text area in which we can load and work with files. (The JFileChooser created by Editor is shown in Figure 14.11.) We’ll stop just shy of the capability to save and let you fill in the blanks (with a few caveats):

Using a JFileChooser

Figure 14-11. Using a JFileChooser

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;

public class Editor
    extends JFrame
    implements ActionListener {
  public static void main(String[] s) { new Editor( ); }

  private JEditorPane textPane = new JEditorPane( );
  
  public Editor( ) {
    super("Editor v1.0");
    addWindowListener(new WindowAdapter( ) {
      public void windowClosing(WindowEvent e) { System.exit(0); }
    });
    Container content = getContentPane( );
    content.add(new JScrollPane(textPane), BorderLayout.CENTER);
    JMenu menu = new JMenu("File");
    menu.add(makeMenuItem("Open"));
    menu.add(makeMenuItem("Save"));
    menu.add(makeMenuItem("Quit"));
    JMenuBar menuBar = new JMenuBar( );
    menuBar.add(menu);
    setJMenuBar(menuBar);
    setSize(300, 300);
    setLocation(200, 200);
    setVisible(true);
  }
  
  public void actionPerformed(ActionEvent e) {
    String command = e.getActionCommand( );
    if (command.equals("Quit")) System.exit(0);
    else if (command.equals("Open")) loadFile( );
    else if (command.equals("Save")) saveFile( );
  }
  
  private void loadFile ( ) {
    JFileChooser chooser = new JFileChooser( );
    int result = chooser.showOpenDialog(this);
    if (result == JFileChooser.CANCEL_OPTION) return;
    try {
      File file = chooser.getSelectedFile( );
      java.net.URL url = file.toURL( );
      textPane.setPage(url);
    }
    catch (Exception e) {
      textPane.setText("Could not load file: " + e);
    }
  }
  
  private void saveFile( ) {
    JFileChooser chooser = new JFileChooser( );
    chooser.showSaveDialog(this);
    // Save file data...
  }
  
  private JMenuItem makeMenuItem( String name ) {
    JMenuItem m = new JMenuItem( name );
    m.addActionListener( this );
    return m;
  }
}

Editor is a JFrame that lays itself out with a JEditorPane (which will be covered in the next chapter) and a pull-down menu. From the pull-down File menu, we can Open, Save, or Quit. The actionPerformed( ) method catches the events associated with these menu selections and takes the appropriate action.

The interesting parts of Editor are the private methods loadFile( ) and saveFile( ).loadFile( ) creates a new JFileChooser and calls its showOpen-Dialog( ) method.

A JFileChooser does its work when the showOpenDialog( ) method is called. This method blocks the caller until the dialog completes its job, at which time the file chooser disappears. After that, we can retrieve the designated file with the getFile( ) method. In loadFile( ), we convert the selected File to a URL and pass it to the JEditorPane, which displays the selected file. As you’ll learn in the next chapter, JEditorPane can display HTML and RTF files.

You can fill out the unfinished saveFile( ) method if you wish, but it would be prudent to add the standard safety precautions. For example, you could use one of the confirmation dialogs we just looked at to prompt the user before overwriting an existing file.

The Color Chooser

Swing is chock full of goodies. JColorChooser is yet another ready-made dialog supplied with Swing; it allows your users to choose colors. The following very brief example shows how easy it is to use JColorChooser:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class LocalColor {
  public static void main(String[] args) {
    final JFrame f = new JFrame("LocalColor v1.0");
    f.addWindowListener(new WindowAdapter( ) {
      public void windowClosing(WindowEvent e) { System.exit(0); }
    });
    f.setSize(200, 200);
    f.setLocation(200, 200);
    final Container content = f.getContentPane( );
    content.setLayout(new GridBagLayout( ));
    JButton button = new JButton("Change color...");
    content.add(button);
    
    button.addActionListener(new ActionListener( ) {
      public void actionPerformed(ActionEvent e) {
        Color c = JColorChooser.showDialog(f,
            "Choose a color", content.getBackground( ));
        if (c != null) content.setBackground(c);
      }
    });
    
    f.setVisible(true);
  }
}

This example shows a frame window with a single button. When you click on the button, a color chooser pops up. After you select a color, it becomes the background color of the frame window.

Basically all we have to do is call JColorChooser’s static method showDialog( ) . In this example, we’ve specified a parent component, a dialog title, and an initial color value. But you can get away with just specifying a parent component. Whatever color the user chooses is returned; if the user presses the Cancel button, null is returned.

Get Learning Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.