Show a message dialog with JOptionPane



This code example shows how to easily display a message dialog using the Swing class JOptionPane.

The message dialog will look like this:

dialog_0

If you want a custom icon on the dialog you can create an instance of the Icon class and as a fifth parameter to showMessageDialog().
In the example above we use the type INFORMATION_MESSAGE, but other types available are:

There are also a number of other types of dialogs that can be displayed with JOptionPane. The example below shows the most common ones.
First we show the same dialog as above, namely a message dialog but this time we set the type to be a warning message instead of information message.

The second dialog is a confirmation dialog that can be used if we want the user to be able to select ‘yes’, ‘no’ or ‘cancel’. The method showConfirmDialog() also has a return value that shows what option the user has made. We use that value to show another message dialog with the user selection.

The third type of dialog is an input dialog. Here we can let the user type something that will be returned from the showInputDialog() method. The parameter types are the same as for the other two dialog types above.

The fourth type is an option dialog. The difference in parameters from the other types is that we here also provide an Object array of options (in the example an array of String objects) and also a parameter that states which of the options that is the default option. In the example above we just hit the enter key when it is displayed, selecting the default option. Remember that the first index of the array of options is 0.

Below is the code example and below the code example are the dialogs displayed.

And here are the dialogs in the order they appear:

Message Dialog

Message Dialog

Confirm Dialog

Confirm Dialog

Message Dialog

Message Dialog

Input Dialog

Input Dialog

Message Dialog

Message Dialog

Option Dialog

Option Dialog

Message Dialog

Message Dialog







Search for more Java info on this site here:
Custom Search


Please type any questions here.