Java Reference
In-Depth Information
1
// Fig. 3.13: NameDialog.java
2
// Obtaining user input from a dialog.
3
4
5
import
javax.swing.JOptionPane;
public
class
NameDialog
6
{
7
public
static
void
main(String[] args)
8
{
9
// prompt user to enter name
String name = JOptionPane.showInputDialog(
"What is your name?"
);
10
11
12
// create the message
String message =
String.format(
"Welcome, %s, to Java Programming!"
, name);
13
14
15
16
// display the message to welcome the user by name
JOptionPane.showMessageDialog(
null
, message);
17
18
}
// end main
19
}
// end class NameDialog
Fig. 3.13
|
Obtaining user input from a dialog.
JOptionPane
Class
static
Method
showInputDialog
Line 10 uses
JOptionPane
method
showInputDialog
to display an input dialog containing
a prompt and a
field
(known as a
text field
) in which the user can enter text. Method
show-
InputDialog
's argument is the prompt that indicates what the user should enter. The user
types characters in the text field, then clicks the
OK
button or presses the
Enter
key to re-
turn the
String
to the program. Method
showInputDialog
returns a
String
containing
the characters typed by the user. We store the
String
in variable
name
. If you press the
dialog's
Cancel
button or press the
Esc
key, the method returns
null
and the program dis-
plays the word “null” as the name.
String
Class
static
Method
format
Lines 13-14 use
static
String
method
format
to return a
String
containing a greeting
with the user's name. Method
format
works like method
System.out.printf
, except that
format
returns the formatted
String
rather than displaying it in a command window.
Line 17 displays the greeting in a message dialog, just as we did in Fig. 3.12.
GUI and Graphics Case Study Exercise
3.1
Modify the addition program in Fig. 2.7 to use dialog-based input and output with the
methods of class
JOptionPane
. Since method
showInputDialog
returns a
String
, you must convert
the
String
the user enters to an
int
for use in calculations. The
static
method
parseInt
of class
Integer
(package
java.lang
) takes a
String
argument representing an integer and returns the value
as an
int
. If the
String
does not contain a valid integer, the program will terminate with an error.