Java Reference
In-Depth Information
An input dialog box prompts the user to enter an input graphically.
Key
Point
You can obtain input from the console. Alternatively, you can obtain input from an input dia-
log box by invoking the
JOptionPane.showInputDialog
method, as shown in Figure 2.4.
JOptionPane
class
String input =
JOptionPane.showInputDialog(
"Enter an input"
);
Click
OK
to accept
input and close
the dialog
Click
Cancel
to close the
dialog without input
F
IGURE
2.4
The input dialog box enables the user to enter a string.
When this method is executed, a dialog is displayed to enable you to enter an input value.
After entering a string, click
OK
to accept the input and close the dialog box. The input is
returned from the method as a string.
There are several ways to use the
showInputDialog
method. For the time being, you
need to know only two ways to invoke it.
One is to use a statement like this one:
showInputDialog
method
JOptionPane.showInputDialog(x);
where
x
is a string for the prompting message.
The other is to use a statement such as the following:
String string = JOptionPane.showInputDialog(
null
, x,
y, JOptionPane.QUESTION_MESSAGE);
where
x
is a string for the prompting message and
y
is a string for the title of the input dialog
box, as shown in the example below.
String input =
JOptionPane.showInputDialog(
null
,
"Enter an input"
,
"Input Dialog Demo"
,
JOptionPane.QUESTION_MESSAGE);
2.19.1 Converting Strings to Numbers
The input returned from the input dialog box is a string. If you enter a numeric value such as
123
,
it returns
"123"
. You have to convert a string into a number to obtain the input as a number.
To convert a string into an
int
value, use the
Integer.parseInt
method, as follows:
Integer.parseInt
method
int
intValue = Integer.parseInt(intString);
where
intString
is a numeric string such as
123
.
To convert a string into a
double
value, use the
Double.parseDouble
method, as follows:
Double.parseDouble
method
double
doubleValue = Double.parseDouble(doubleString);
where
doubleString
is a numeric string such as
123.45
.
The
Integer
and
Double
classes are both included in the
java.lang
package, and thus
they are automatically imported.