Java JOptionPane class

Introduction

To create simple, standard dialogs, use the JOptionPane class.

The following constants are defined in JOptionPane to show different icons:

  • ERROR_MESSAGE
  • INFORMATION_MESSAGE
  • WARNING_MESSAGE
  • QUESTION_MESSAGE
  • PLAIN_MESSAGE

The following instantly shows a simple message dialog:

JOptionPane.showMessageDialog(f, "How easy to create dialogs!"); 

Input Dialog

These kinds of dialog boxes are used to take input from the users.

They are created using showInputDialog() method.

The simplest one creates a dialog with one text field where users can provide data.

Here is an example:

String s = (String)JOptionPane.showInputDialog(f, ?Your name please? ); 

Confirm Dialog

Confirm Dialog can ask the user to confirm something.

They are created using showConfirmDialog() method.

The type of buttons to be displayed may be customized using static constants defined in JOptionPane class.

For example, YES_NO_OPTION dialogs have two buttons.

YES_NO_CANCEL_OPTION dialogs have three buttons.

The following creates a dialog with two buttons.


int n = JOptionPane.showConfirmDialog(f,"Confirm to exit?", "Confirmaton",JOptionPane.YES_NO_OPTION); 

This method returns an integer indicating the user's action.

The possible values are

  • YES_OPTION,
  • NO_OPTION,
  • CANCEL_OPTION,
  • OK_OPTION, and
  • CLOSED_OPTION.

Each option, except for CLOSED_OPTION, correspond to the button pressed.

The CLOSED_OPTION is returned, if dialog window is closed explicitly, rather than pressing a button inside the option pane.

Option Dialog

The option dialog boxes display a variety of buttons with customized button text.

They can contain a standard text message or a collection of components.

These are created using showOptionDialog().

When using showOptionDialog() and showConfirmDialog() we can either use the standard button text or specify different text.

For example, the following creates a dialog with two buttons captioned "Pay now" and "Pay later".

String[] options = {"Pay now","Pay later"};  
int n = JOptionPane.showOptionDialog(f,"Pay option","Pay dialog",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);  

This method returns an integer similar to showConfirmDialog() method. 



PreviousNext

Related