JOptionPane makes it easy to pop up a standard dialog box that prompts the user for information or displays some information.
The labels of the option-buttons displayed within the popup dialog can be customized by changing static variables in the JOptionPane class. Similarly, "accelerator keys" can be set to have the same effect as the option-buttons. For example, the following code would set the label of the OK button to "OK (F1)", and set the F1 key to have the same effect as the OK button:
JOptionPane.OK_LABEL = "OK (F1)"; JOptionPane.OK_ACCELERATOR = KeyEvent.VK_F1;
Note that after the buttons have been customized, they stay customized for all future invocations of the JOptionPane "showXXXDialog()" methods.
The parameters to these methods follow consistent patterns:
- Defines the Component that is to be the parent of this dialog box. It is used in two ways: its screen coordinates are used in the placement of the dialog box, and the dialog box inherits its foreground and background colors from
parentComponent(unless the the JOptionPane's colors have been set explicitly). In general, the dialog box centered on top of
parentComponent. This parameter may be null, in which case a default Frame is used as the parent, and the dialog will be centered on the screen.
- A descriptive message to be placed in the dialog box. In the most common usage, message is just a String or String constant. However, the type of this parameter is actually Object. Its interpretation depends on its type:
- The string is displayed as a message on one line.
- An array of Objects is interpreted as a series of messages arranged in a vertical stack. Each Object is converted to a String using its toString() method. The result is wrapped in a JLabel and displayed.
- Defines the style of the message. The possible values are:
- Defines the set of option buttons that appear at the bottom of the dialog box:
You aren't limited to this set of option buttons. You can provide any buttons you want using the
- A more detailed description of the set of option buttons that will appear at the bottom of the dialog box. The usual value for the options parameter is an array of Strings. But the parameter type is an array of Objects. A button is created for each object depending on its type:
- The component is added to the button row directly.
- The Object is converted to a string using its toString method and the result is used to label a JButton.
- This parameter is used in javax.Swing to specify a decorative icon to be placed in the dialog box. It is ignored by Charva.
- The title for the dialog box.
- The default selection (input value).