2.6 Dialog Boxes for Input /Output
A dialog box is a small graphical window that displays a message to the user or requests input. Two of the dialog boxes are: –
Message Dialog - a dialog box that displays a message.
Input Dialog - a dialog box that prompts the user for input.
The ‘javax.swing.JOptionPane’ class offers dialog box methods. The following statement must be before the program’s class header:
import javax.swing.JOptionPane;
Message Dialog Box
Syntax :
JOptionPane.showMessageDialog (null, <message> )
import javax.swing.JOptionPane; // Needed for Dialog Box
/**
* This program demonstrates
* showMessageDialog.
*/
public class MessageDialogDemo
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "Welcome");
}
}
Output :
Input Dialog
Syntax :
<String variable> = JOptionPane.showInputDialog (<message> )
Reading String Input
import javax.swing.JOptionPane; // Needed for Dialog Box
/**
* This program demonstrates
* showInputDialog.
*/
public class InputDialogDemo
{
public static void main(String[] args)
{
String name;
// Get the user's name.
name = JOptionPane.showInputDialog("What is your name? ");
// Display message
JOptionPane.showMessageDialog(null, "Hello " + name);
}
}
Program Output
Reading Number Input
The JOptionPane’s showInputDialog method always returns the user's input as a String. String containing a number, such as "15", can be converted to a numeric data type.
The Parse Methods
Each of the numeric wrapper classes (discussed later), has a parse method that converts a string to a number.
int iVar = Integer.parseInt("259"); // Store 259 in iVar.
double dVar = Double.parseDouble("794.6"); // Store 794.6 in dVar.
Look at the following example program :
import javax.swing.JOptionPane; // Needed for Dialog Box
/** * This program find area of rectangle * using input output dialog box. */ public class RectangleTest { public static void main(String[] args) { String input; // To hold String input. int length; // To hold length. int width; // To hold width. int area; // To hold area. // Prompt user to input length. input = JOptionPane.showInputDialog("Enter Length"); // Convert the String input to an int. length = Integer.parseInt(input); // Prompt user to input width. input = JOptionPane.showInputDialog("Enter Width"); // Convert the String input to an int. width = Integer.parseInt(input); // Calculate area of rectangle. area = length * width; // Display area of rectangle. JOptionPane.showMessageDialog(null, "Area of rectangle is " + area); } }
Output :