Java Reference
In-Depth Information
The window may look slightly different in different operating systems, but the
message will be the same.
The preceding program uses a static method in the JOptionPane class called
showMessageDialog . This method accepts two parameters: a parent window and a mes-
sage string to display. We don't have a parent window in this case, so we passed null .
JOptionPane can be used in three major ways: to display a message (as just
demonstrated), to present a list of choices to the user, and to ask the user to type
input. The three methods that implement these three behaviors are called
showMessageDialog , showConfirmDialog , and showInputDialog , respectively.
These methods are detailed in Table 14.1.
Table 14.1
Useful Methods of the JOptionPane Class
Method
Description
showConfirmDialog(parent, Shows a Yes/No/Cancel message box containing the given
message) message on the screen and returns the choice as an int with
one of the following constant values:
JOptionPane.YES_OPTION (user clicked “Yes”)
JOptionPane.NO_OPTION (user clicked “No”)
JOptionPane.CANCEL_OPTION (user clicked “Cancel”)
showInputDialog(parent, Shows an input box containing the given message on the
message) screen and returns the user's input value as a String
showMessageDialog(parent, Shows the given message string in a message box on the
message)
screen
The following program briefly demonstrates all three types of option panes:
1 // Shows several JOptionPane windows on the screen.
2
3 import javax.swing.*; // for GUI components
4
5 public class UseOptionPanes {
6 public static void main(String[] args) {
7 // read the user's name graphically
8 String name = JOptionPane.showInputDialog( null ,
9
"What is your name?");
10
11 // ask the user a yes/no question
12 int choice = JOptionPane.showConfirmDialog( null ,
 
Search WWH ::




Custom Search