Java Reference
In-Depth Information
12
String secondNumber =
JOptionPane.showInputDialog(
"Enter second integer"
);
13
14
15
// convert String inputs to int values for use in a calculation
16
int
number1 = Integer.parseInt(firstNumber);
17
int
number2 = Integer.parseInt(secondNumber);
18
19
int
sum = number1 + number2;
20
21
// display result in a JOptionPane message dialog
JOptionPane.showMessageDialog(
null
,
"The sum is "
+ sum,
"Sum of Two Integers"
,
JOptionPane.PLAIN_MESSAGE
);
22
23
24
}
25
}
// end class Addition
(a) Input dialog displayed by lines 10-11
Prompt to the user
Text field in which the
user types a value
When the user clicks
OK
,
showInputDialog
returns
to the program the
100
typed
by the user as a
String
; the
program must convert the
String
to an
int
(b) Input dialog displayed by lines 12-13
(c) Message dialog displayed by lines 22-23—When the user clicks
OK
, the message dialog is dismissed (removed from the screen)
Fig. 12.2
|
Addition program that uses
JOptionPane
for input and output. (Part 2 of 2.)
Input Dialogs
Line 3 imports class
JOptionPane
. Lines 10-11 declare the local
String
variable
first-
Number
and assign it the result of the call to
JOptionPane
static
method
showInputDia-
log
. This method displays an input dialog (see the screen capture in Fig. 12.2(a)), using
the method's
String
argument (
"Enter
first
integer"
) as a prompt.
Look-and-Feel Observation 12.2
The prompt in an input dialog typically uses
sentence-style capitalization
—a style that
capitalizes only the first letter of the first word in the text unless the word is a proper noun
(for example, Jones).
The user types characters in the text field, then clicks
OK
or presses the
Enter
key to
submit the
String
to the program. Clicking
OK
also
dismisses
(
hides
)
the dialog
. [
Note:
If you type in the text field and nothing appears, activate the text field by clicking it with
the mouse.] Unlike
Scanner
, which can be used to input values of
several
types from the
user at the keyboard,
an input dialog can input only
String
s
. This is typical of most GUI