Modal UI elements with JOptionPane

It is not uncommon to have to present a message to a user, ask the user to confirm an action, or even prompt the user for some input. Typically we do this with a modal view, and in Java the JOptionPane class provides us with the functionality do handle all of these requirements.

JOptionPane provides static methods (i.e. we don't need an instance of JOptionPane to use them) which allow us to do four common tasks:

Message Dialogue

The simplest of these functions is to inform the user. Here, we simply call the JOptionPanel.showMessage() method. This method makes use of operator overloading, so we can call it with a variety of different parameters. The simplest requires a parent GUI component (which can be null) and a message as follows:

//option pane displayed in default location, with a message
JOptionPane.showMessageDialog(null,"Here is an important message");
    
//option pane displayed in location relative to parent component (in this case named rootPanel), with a message
JOptionPane.showMessageDialog(rootPanel,"Here is an important message");
This would render as follows: JOptionPanel message dialogue

We can also customise the panel further by specifying a title for the error dialogue box and the type of error message as follows:

//option pane (default location), with message, title and Information message type
JOptionPane.showMessageDialog(null,"Here is an important message","Important message",JOptionPane.INFORMATION_MESSAGE);
///option pane (default location), with message, title and Warning message type
JOptionPane.showMessageDialog(null,"Here is a warning message","Warning",JOptionPane.WARNING_MESSAGE);
The latter of these message would display as follows: JOptionPanel message dialogue

The other message types that can be used are as follows: ERROR_MESSAGE,QUESTION_MESSAGE and PLAIN_MESSAGE

Confirmation Dialogue

Providing a dialogue box that asks the user to confirm is a little more complex. The method used this time is JOptionPane.showConfirmDialog(). This time we will be interested in the value that is returned from the method (so we know what the users intention is) and again there are a series of overloads available. Example code for calling the method with the fewest parameters would be as follows:

int optionResult = JOptionPane.showConfirmDialog(null, "Are you sure");
This would display the following dialogue box: JOptionPane default confirm dialogueWe should note that the method returns an int value, and the JOptionPane class contains a number of constants which provide a name for the returned value. This enables us to evaluate the result as follows:
if (optionResult == JOptionPane.YES_OPTION) {
    //use has confirmed, do something
}
The other constants which can be used for verifying an option as as follows: NO_OPTION,CANCEL_OPTION,OK_OPTION and CLOSED_OPTION

We can provide a title for the dialogue box and specify an alternate set of confirmation / rejection buttons with additional overloads as follows:

//this dialogue box would only give OK and Cancel options
int optionResult = JOptionPane.showConfirmDialog(null, "Are you sure","Please confirm",JOptionPane.OK_CANCEL_OPTION);
The other predefined constants for specifying the option type buttons are as follows: DEFAULT_OPTION,YES_NO_OPTION and YES_NO_CANCEL_OPTION. Be aware that OK and YES are two different options.

Input dialogue

JOptionPane also allows us to collect information from the user. These should be used sparingly as entering data into a series of modal dialogue boxes offers a poor user experience. Interestingly the showInputDialogue() method doesn't require us to specify a parent component, though we may. The following example shows how we can use the method to prompt the user for a String and store it in a variable:

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

We can also specify an initial selection value, which will pre-populate the input field with a value - the example below does this, and the screen capture shows the result:
String userInput = JOptionPane.showInputDialog("Please enter your name","Anonymous");
JOptionPane with pre-define text input

Option Dialogue

We can combine elements of the above dialogue boxes with an Option Dialogue. This allows us to specify a parent component, message, title, they type of options, the type of message, a series of options and an initial value if required. Consider the following example (the method parameters have been placed on multiple lines to enable commenting, but typically they might be displayed on one line):

//create options
String[] possibleValues = {"Spades", "Hearts", "Clubs", "Diamonds"};

//create dialogue with options and store index of selection item in variable
int selection = JOptionPane.showOptionDialog(
        null,                         //parent component
        "Please make a choice",       //message
        "Choose one",                 //title
        JOptionPane.DEFAULT_OPTION,   //option type (overridden by specified options)
        JOptionPane.QUESTION_MESSAGE, //type of dialogue
        null,                         //icon
        possibleValues,               //possible options
        possibleValues[0]             //pre-selected option
);

//determine the choice based on the index of the selection
String choice = possibleValues[selection];
This would render a selection box as shown below: Custom JOptionPane dialogueIt is possible to use an array of objects of any type instead of strings, though the dialogue box will display the result of calling each object's toString() method.