Alert Dialogs (JOptionPane)

1. JOptionPane Basics

Static methods in the JOptionPane class let you easily create modal dialogs to show messages (JOptionPane.showMessageDialog), to ask for confirmation (JOptionPane.showConfirmDialog), to let the user enter text or to choose among predefined options (JOptionPane.showInputDialog), or to choose among a variety of buttons (JOptionPane.showOptionDialog). Each of these methods either returns an int specifying which button was pressed, or a String specifying the option selected.

2. Example Confirm Dialogs

Following are the four standard varieties of confirmation dialogs available via JOptionPane.showMessageDialog, shown with the Windows LAF. Note that they were interactively created via JOptionPaneExamples.java, which lets you interactively choose among the various dialog types and options, then pop up samples of your selections with different LAFs. See the source code at the bottom of this page.

Default Default Confirm Dialog
Yes/No Yes/No Confirm Dialog
Yes/No/Cancel Yes/No/Cancel Confirm Dialog
Default OK/Cancel Confirm Dialog

3. Example Message Dialogs

Following are the five standard varieties of message dialogs available via JOptionPane.showMessageDialog, shown with the Windows, Java, and Motif LAFs. Note that they were interactively created via JOptionPaneExamples.java, which lets you interactively choose among the various dialog types and options, then pop up samples of your selections with different LAFs. See the source code at the bottom of this page.

Windows LAF Java LAF Motif LAF
Plain Plain Message -- Windows LAF Plain Message -- Java LAF Plain Message -- Motif LAF
Info Info Message -- Windows LAF Info Message -- Java LAF Info Message -- Motif LAF
Question Question Message -- Windows LAF Question Message -- Java LAF Question Message -- Motif LAF
Warning Warning Message -- Windows LAF Warning Message -- Java LAF Warning Message -- Motif LAF
Error Error Message -- Windows LAF Error Message -- Java LAF Error Message -- Motif LAF

4. Interactive Dialog Creator

To get a feel for the various standard dialog types, the following example lets you interactively choose the type of dialog, the messages and other options, and the look-and-feel.

JOptionPaneExamples.java (Download source code)

See the links following the source code for additional classes used by JOptionPaneExamples.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.StringTokenizer;

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

  private JButton popupDialogButton;
  private JRadioButton[] dialogTypeButtons;
  private JRadioButton[] messageTypeButtons;
  private int[] messageTypes =
    { JOptionPane.PLAIN_MESSAGE, JOptionPane.INFORMATION_MESSAGE, 
      JOptionPane.QUESTION_MESSAGE, JOptionPane.WARNING_MESSAGE, 
      JOptionPane.ERROR_MESSAGE };
  private JLabeledTextField titleField, messageField, selectionValuesField, 
                            buttonLabelsField, focusedButtonField;
  private JCheckBox ignoreSelectionValuesBox;
  private ButtonGroup messageTypeButtonGroup, buttonTypeButtonGroup,
                      dialogTypeButtonGroup;
  
  private JRadioButton[] buttonTypeButtons;
  private int[] buttonTypes =
    { JOptionPane.DEFAULT_OPTION, JOptionPane.YES_NO_OPTION, 
      JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.OK_CANCEL_OPTION };
  
  private JCheckBox[] lookAndFeelBoxes;

  public JOptionPaneExamples() {
    super("JOptionPane Examples");
    addWindowListener(new ExitListener());
    WindowUtilities.setNativeLookAndFeel();
    Container content = getContentPane();
    content.setLayout(new GridLayout(0, 1));

    JPanel buttonPanel = new JPanel();
    popupDialogButton = new JButton("Show Option Pane(s)");
    popupDialogButton.addActionListener(this);
    buttonPanel.add(popupDialogButton);
    content.add(buttonPanel);
    dialogTypeButtonGroup = new ButtonGroup();
    dialogTypeButtons = 
      new JRadioButton[] { new JRadioButton("Show Message", true),
                           new JRadioButton("Get Confirmation"),
			               new JRadioButton("Collect Input"),
			               new JRadioButton("Present Options") };
    content.add(new RadioButtonPanel("Dialog type:", dialogTypeButtons, 
				     dialogTypeButtonGroup));

    messageTypeButtonGroup = new ButtonGroup();
    messageTypeButtons =
      new JRadioButton[] { new JRadioButton("Plain"), 
			               new JRadioButton("Information", true),
			               new JRadioButton("Question"), 
			               new JRadioButton("Warning"), 
			               new JRadioButton("Error") };
    content.add(new RadioButtonPanel("Option Pane Type:", messageTypeButtons, 
				messageTypeButtonGroup));

    lookAndFeelBoxes = 
      new JCheckBox[] { new JCheckBox("Native", true), 
                        new JCheckBox("Java (Metal)"),
			            new JCheckBox("Motif") };
    content.add(new CheckBoxPanel("Looks to use:", lookAndFeelBoxes));

    titleField = 
      new JLabeledTextField("Title:", "Title to appear at top of border");
    content.add(titleField);
    messageField = 
      new JLabeledTextField("Message:", "Message to appear inside of dialog box");
    content.add(messageField);

    buttonTypeButtonGroup = new ButtonGroup();
    buttonTypeButtons =
      new JRadioButton[] { new JRadioButton("Default", true), 
			               new JRadioButton("Yes/No"), 
			               new JRadioButton("Yes/No/Cancel"), 
			               new JRadioButton("OK/Cancel") };
    RadioButtonPanel buttonLabelPanel =
      new RadioButtonPanel("Button Labels:", buttonTypeButtons, 
			               buttonTypeButtonGroup);
    DisableListener.addEnabler(dialogTypeButtons[1], buttonLabelPanel);
    content.add(buttonLabelPanel);

    selectionValuesField = 
      new JLabeledTextField("Choices to present to user (separate by spaces):",
			                "Choice1 Choice2 Choice3 Choice4");
    content.add(selectionValuesField);

    ignoreSelectionValuesBox = 
      new JCheckBox("Ignore predefined choices and supply textfield to user");
    DisableListener.addDisabler(ignoreSelectionValuesBox, selectionValuesField);   
    DisableListener.addEnabler(dialogTypeButtons[2], selectionValuesField);
    DisableListener.addEnabler(dialogTypeButtons[2], ignoreSelectionValuesBox);
    content.add(ignoreSelectionValuesBox);

    buttonLabelsField =
      new JLabeledTextField("Button labels for \"Option\" dialog:",
			                "Button1 Button2 Button3");
    DisableListener.addEnabler(dialogTypeButtons[3], buttonLabelsField); 
    content.add(buttonLabelsField);
    
    pack();
    setVisible(true);
  }

  public void actionPerformed(ActionEvent event) {
    if (lookAndFeelBoxes[0].isSelected()) {
      WindowUtilities.setNativeLookAndFeel();
      popUpDialog();
    } 
    if (lookAndFeelBoxes[1].isSelected()) {
      WindowUtilities.setJavaLookAndFeel();
      popUpDialog();
      WindowUtilities.setNativeLookAndFeel();
    } 
    if (lookAndFeelBoxes[2].isSelected()) {
      WindowUtilities.setMotifLookAndFeel();
      popUpDialog();
      WindowUtilities.setNativeLookAndFeel();
    } 
  }

  private void popUpDialog() {
    if (dialogTypeButtons[0].isSelected())
      JOptionPane.showMessageDialog(this, messageField.getText(),
				                       titleField.getText(), getMessageType());
    else if (dialogTypeButtons[1].isSelected())
      JOptionPane.showConfirmDialog(this, messageField.getText(),
				                       titleField.getText(), getButtonType(),
				                       getMessageType());
    else if (dialogTypeButtons[2].isSelected()) {
      String[] selections;
      if (selectionValuesField.isEnabled())
        selections = substrings(selectionValuesField.getText());
      else
        selections = null;
      JOptionPane.showInputDialog(this, messageField.getText(),
				                     titleField.getText(), getMessageType(),
				                     null, selections, null);
    } else if (dialogTypeButtons[3].isSelected())
      JOptionPane.showOptionDialog(this, messageField.getText(),
				                      titleField.getText(), getButtonType(),
				                      getMessageType(), null,
				                      substrings(buttonLabelsField.getText()),
				                      null);
  }
   
  private int getAssociatedType(AbstractButton[] buttons, int[] types) {
    for(int i=0; i<buttons.length; i++)
      if (buttons[i].isSelected())
        return(types[i]); 
    return(types[0]);
  }

  private int getMessageType() {
    return(getAssociatedType(messageTypeButtons, messageTypes));
  }
    
  private int getButtonType() {
    return(getAssociatedType(buttonTypeButtons, buttonTypes));
  }

  private String[] substrings(String string) {
    StringTokenizer tok = new StringTokenizer(string);
    String[] substrings = new String[tok.countTokens()];
    for(int i=0; i<substrings.length; i++)
      substrings[i] = tok.nextToken();
    return(substrings);
  }
}

class CheckBoxPanel extends JPanel {
  public CheckBoxPanel(String labelString, JCheckBox[] checkBoxes) {
    setLayout(new FlowLayout(FlowLayout.LEFT));
    add(new JLabel(labelString));
    for(int i=0; i<checkBoxes.length; i++) {
      add(checkBoxes[i]);
    }
  }
}
Note: also requires JLabeledTextField.java, RadioButtonPanel.java, and DisableListener.java as well as WindowUtilities.java and ExitListener.java, shown earlier.


This page is part of my Quick Swing Tutorial for AWT Programmers. © 1999 Marty Hall. All source code freely available for unrestricted use. Created for for work in the Research and Technology Development Center of the Johns Hopkins University Applied Physics Lab, for courses in the Johns Hopkins Part-Time MS Program in Computer Science, and for various industry seminars and Java short courses.