Thursday, January 22, 2009

Java: JOptionPane Dialog Examples Part 1 - Basic

Java has a huge amount of functionality for creating GUI's for your applications. Some of the more complex GUI's require lots of code. However, sometimes you just need a plain old, nothing fancy, quick-and-dirty, keep it simple dialog. In these situations, the JOptionPane works really well. Basic JOptionPane dialog examples are the core of this article.

Although it's Java's workhouse dialog, there are a few limitations. It helps to understand those limitations such that it fulfills your expectations. The first limitation (some consider this a feature) is modality. The thread which creates the JOPtionPane dialog will wait until the user closes the dialog. The other limitation is that it cannot be resized. The user won't be able to make the dialog bigger in order to see its contents better.

If these limitations are cramping your style, you'll need to move towards JDialog based dialogs. Otherwise, read on for more JOptionPane information.


The Methods

There are four commonly used static methods for JOPtionPane dialogs:

  • showMessageDialog()
  • showInputDialog()
  • showConfirmDialog()
  • showOptionDialog()

All four methods allow for an icon on the left hand side and one or more buttons along the bottom. Both of these are controllable and behave somewhat differently depending on which method is used.

All three of showMessageDialog(), showConfirmDialog(), and showOptionDialog() are capable of displaying some form of information to the user, but each allows the user to respond in different ways. showMessageDialog() allows for only for a message and an OK button. showConfirmDialog() allows for various combinations of OK, YES, NO, and CANCEL buttons. showOptionDialog() allows you to display buttons containing the text of your choice.

Only showInputDialog() allows for the user to enter arbitrary information either in a text field or with a combo-box style list of values. It provides only OK and CANCEL buttons.


Message Types

All four dialog types have options to display a predefined icon. The following icon types are listed below, each of which is a static field of the JOptionPane class. The actual icons displayed depends upon the java look and feel active at that time.

  • JOptionPane.ERROR_MESSAGE -- red letter x, or a "no entry" sign
  • JOptionPane.INFORMATION_MESSAGE -- letter i in a circle
  • JOptionPane.WARNING_MESSAGE -- excalamation point
  • JOptionPane.QUESTION_MESSAGE -- question mark
  • JOptionPane.PLAIN_MESSAGE -- no standard icon


Option Types

The showConfirmDialog() and showOptionDialog() methods have provisions for an "option type", which are the buttons that will be displayed.

  • JOptionPane.DEFAULT_OPTION -- OK button
  • JOptionPane.YES_NO_OPTION -- YES and NO buttons
  • JOptionPane.YES_NO_CANCEL_OPTION -- YES, NO, and CANCEL buttons
  • JOptionPane.OK_CANCEL_OPTION -- OK and CANCEL buttons


Return Values

Both showConfirmDialog() and showOptionDialog() return an int that you can use to figure out how the user responded to the dialog. Did they hit YES, NO, or OK? Just analyze the value using the list below. Perhaps the user closed the dialog window and did not hit one of your buttons? It's an important piece of logic to add to your program.

  • JOptionPane.YES_OPTION -- YES button
  • JOptionPane.OK_OPTION -- OK button
  • JOptionPane.NO_OPTION -- NO button
  • JOptionPane.CANCEL_OPTION -- CANCEL button
  • JOptionPane.CLOSED_OPTION -- User closed the dialog without using a button

For what it's worth, YES_OPTION and OK_OPTION are actually the same value.


Parent Component

In these examples, null is used for the parent component, which creates a standalone dialog, usually centered on the screen. A parent UI component can be used to center the dialog on that component if that is desireable.


User Specified Icon

Some of the method signatures allow for a user specified icon to be used in the dialog box. Even if a particular message type is requested, if a non-null ImageIcon is supplied, that icon will be used in the dialog. This parameter is always optional. null can be used wherever an icon needs to be specified.

Beyond the scope of this article is placement of the icon file. The presumption of this article is that the icon file is in the working directory of the java process. In a more practical application, you will want to locate the icon file in your jar file or in a specific folder. Each of these approaches has a different set of steps to define and will be discussed in a future article.


Method: showMessageDialog()

The dialog produced by showMessageDialog() is a basic dialog displaying a message to the user. The user will see your message with only an "OK" button to close the dialog. No value is returned.


Example 1a: Dialog displaying "Hello!", with OK button, standard "info" icon, and title "Message".

JOptionPane.showMessageDialog(null, "Hello!");
 

Example 1b: Dialog displaying "Hello!", with OK button, no standard icon, and title "Message Title".

int messageType = JOptionPane.PLAIN_MESSAGE; // no standard icon

JOptionPane.showMessageDialog(null, "Hello!", "Message Title", messageType);
 

Example 1c: Dialog displaying "Hello!", with OK button, non-standard icon from GIF file, and title "Message Title".

int messageType = JOptionPane.PLAIN_MESSAGE; // no standard icon
ImageIcon icon = new ImageIcon("blob.gif", "blob");

JOptionPane.showMessageDialog(null, "Hello!", "Message Title", messageType, icon);
 


Method: showInputDialog()

showInputDialog() prompts the user for a value from a text field or within a dropdown combo-box style component. The method returns a String.


Example 2a: Dialog with empty text field, "Enter value:" prompt string, plus OK and CANCEL buttons

String res = JOptionPane.showInputDialog("Enter value:");
System.out.println( "showInputDialog: " + res );
 

Example 2b: Dialog with text field initialized to "Hello!", "Enter value:" prompt string, plus OK and CANCEL buttons

String res = JOptionPane.showInputDialog("Enter value:", "Hello!");
System.out.println( "showInputDialog: " + res );
 

Example 2c: Dialog with empty text field, "Enter value:" prompt string, plus OK and CANCEL buttons

String res = JOptionPane.showInputDialog(null, "Enter value:");
System.out.println( "showInputDialog: " + res );
 

Example 2d: Dialog with text field initialized to "Hello!", "Enter value:" prompt string, plus OK and CANCEL buttons

String res = JOptionPane.showInputDialog(null, "Enter value:", "Hello!");
System.out.println( "showInputDialog: " + res );
 

Example 2e: Empty text field, "Enter value:" prompt string, plus OK and CANCEL buttons

int messageType = JOptionPane.PLAIN_MESSAGE; // no standard icon

String res = JOptionPane.showInputDialog(null, "Enter value:", "Message Title", messageType);
System.out.println( "showInputDialog: " + res );
 

Example 2f: Combo box displaying values from selValues array with value initialized to selValues[0], "Enter value:" prompt string, plus OK and CANCEL buttons

Object[] selValues = { "abc", "def", "ghi" };
int messageType = JOptionPane.PLAIN_MESSAGE; // no standard icon
ImageIcon icon = new ImageIcon("blob.gif", "blob");

Object res = JOptionPane.showInputDialog(null, "Enter value:", "Message Title",
messageType, icon, selValues, selValues[0]);

System.out.println( "showInputDialog: " + res );
 


Method: showConfirmDialog()

showConfirmDialog() produces a dialog similar to that from showMessageDialog(), except that it provides more options for buttons. Button combinations available are OK, YES+NO, YES+NO+CANCEL, and OK+CANCEL. The int return value indicates the button pressed, if any.


Example 3a: Dialog displaying "Hello!", with YES+NO+CANCEL buttons, standard "question mark" icon, and title "Select an Option".

int res = JOptionPane.showConfirmDialog(null, "Hello!");
 

Example 3b: Dialog displaying "Hello!", with YES+NO+CANCEL buttons, standard "question mark" icon, and title "Message Title".

int optionType = JOptionPane.YES_NO_CANCEL_OPTION; // YES+NO+CANCEL
int res = JOptionPane.showConfirmDialog(null, "Hello!", "Message Title", optionType);
 

Example 3c: Dialog displaying "Hello!", with YES+NO+CANCEL buttons, no standard icon, and title "Message Title".

int optionType = JOptionPane.YES_NO_CANCEL_OPTION; // YES+NO+CANCEL
int messageType = JOptionPane.PLAIN_MESSAGE; // no standard icon
int res = JOptionPane.showConfirmDialog(null, "Hello!", "Message Title",
optionType, messageType);
 

Example 3d: Dialog displaying "Hello!", with YES+NO+CANCEL buttons, "blob" icon, and title "Message Title". XXX

int optionType = JOptionPane.YES_NO_CANCEL_OPTION; // YES+NO+CANCEL
int messageType = JOptionPane.PLAIN_MESSAGE; // no standard icon
ImageIcon icon = new ImageIcon("blob.gif", "blob");
int res = JOptionPane.showConfirmDialog(null, "Hello!", "Message Title",
optionType, messageType, icon);
 

Example 3e: Handling Return Values of showConfirmDialog()

The int value returned by showConfirmDialog() tells you which button the users pressed, or if they simply closed the dialog without using any buttons at all.

// User hit YES
if (res == JOptionPane.YES_OPTION) { System.out.println( "YES_OPTION" ); }

// User hit OK
if (res == JOptionPane.OK_OPTION) { System.out.println( "OK_OPTION" ); }

// User hit NO
if (res == JOptionPane.NO_OPTION) { System.out.println( "NO_OPTION" ); }

// User hit CANCEL
if (res == JOptionPane.CANCEL_OPTION) { System.out.println( "CANCEL_OPTION" ); }

// User closed the window without hitting any button
if (res == JOptionPane.CLOSED_OPTION) { System.out.println( "CLOSED_OPTION" ); }
 


Method: showOptionDialog()

showOptionDialog() displays buttons whose labels are based on the values in the input array, with one of the buttons being the default option. If one of the buttons is selected, showOptionDialog() returns the array index number of the selected button.

If the dialog is closed without selecting a button, showOptionDialog() returns -1. It seems to ignore the "option type" parameter.

Example 4a: Dialog displaying "Hello!", with button labels from selValues array, "blob" icon, and title "Message Title".

int optionType = JOptionPane.DEFAULT_OPTION;
int messageType = JOptionPane.PLAIN_MESSAGE; // no standard icon
ImageIcon icon = new ImageIcon("blob.gif", "blob");
Object[] selValues = { "abc", "def", "ghi" };

// Shows message, choices appear as buttons
int res = JOptionPane.showOptionDialog(null, "Hello!", "Message Title",
optionType, messageType, icon,
selValues, selValues[0]);
 

Example 4b: Handling Return Values of showOptionDialog()

System.out.println( "showOptionDialog: " + res);

if (res >= 0) {
System.out.println( "showOptionDialog: " + res + " (" + selValues[res] + ")" );
}

if (res == JOptionPane.CLOSED_OPTION) { System.out.println( "CLOSED_OPTION" ); }
 



These are the basic uses of the JOptionPane. As you can see here, for a simple dialog, there are numerous options, and I have only described a fraction of it's capabilities.

In Part 2, I'll discuss some poorly documented features of JOptionPane, but they may just blow your mind.