1. F a i s a l a b a d
1 1 / 2 1 / 2 0 1 3
F. Ansari
This document contain the summary of
JOptionPane class
Javadocx
2. Javadocx
JOptionPane class
JOptionPane is a class in which mostly 4 kinds of dialog boxes can be displayed. A
dialog box is a small graphical window that displays a message to the user or input as
requested by user. There are following types of method used to display dialog boxes.
Method Name Description
showConfirmDialog Asks a confirming question, like yes/no/cancel.
showInputDialog Prompt for some input.
showMessageDialog Tell the user about something that has happened.
showOptionDialog The Grand Unification of the above three.
This class is not available to our java programs but we have to import it by writing
“import javax.swing.JOptionPane;” we use “import javax.swing.JOptionPane;” before
the programs class definition. It tells the compiler where to find the JOptionPane class. It
provides static methods to display each type of dialog box. Dot operator is used to
access the methods of dialog boxes that is JOptionPane.showMessageDialog method is
used to display a message dialog, JOptionPane.showMessageDialog (null, "Hello
World");. The second argument is the message that is to be displayed on the dialog box.
The input dialog box is used to ask the user to enter data. The dialog displays a text field,
an Ok button and a Cancel button. If Ok is pressed, the dialog returns the user’s input. If
Cancel is pressed, the dialog returns null. A program that uses JOptionPane does not
automatically stop executing when the end of the main method is reached. If the
System.exit(0); method is not called, the thread main() continues to execute. The
System.exit(0); method requires an integer argument that is 0. This argument is an exit
code that is passed back to the operating system. This code is usually ignored however it
can be used outside of the program.
For example:
import javax.swing.JOptionPane;
public class NamesDialog
{
public static void main(String[] args)
{
String firstName; // The user's first name
firstName = JOptionPane.showInputDialog("What is " + "your first name? ");
// Get the user's first name
JOptionPane.showMessageDialog(null, "Hello " + firstName + " " +middleName + " " +
lastName); //displays the user’s first name