Java Reference
In-Depth Information
13 "Do you like cake, " + name + "?");
14
15 // show different response depending on answer
16
if
(choice == JOptionPane.YES_OPTION) {
17 JOptionPane.showMessageDialog(
null
,
18 "Of course! Who doesn't?");
19 }
else
{ // choice == NO_OPTION or CANCEL_OPTION
20 JOptionPane.showMessageDialog(
null
,
21
"We'll have to agree to disagree.");
22 }
23 }
24 }
The graphical input and output of this program is a series of windows, which pop
up one at a time:
One limitation of
JOptionPane
is that its
showConfirmDialog
method always
returns the user's input as a
String
. If you'd like to graphically request user input
that is a number instead, your program must convert the
String
using the
Integer.parseInt
or
Double.parseDouble
method. These static methods accept
a
String
as a parameter and return an
int
or
double
value, respectively.
The following program demonstrates the use of
JOptionPane
to read numbers
from the user:
1 // Uses JOptionPane windows for numeric input.
2
3
import
javax.swing.*; // for GUI components
4
5
public class
UseOptionPanes2 {
6
public static void
main(String[] args) {
7 String ageText = JOptionPane.showInputDialog(
null
,
8 "How old are you?");
9
int
age = Integer.parseInt(ageText);
10
11 String moneyText = JOptionPane.showInputDialog(
null
,
12 "How much money do you have?");
13
double
money = Double.parseDouble(moneyText);
14
15 JOptionPane.showMessageDialog(
null
,
16
"If you can double your money each year,\n" +
Search WWH ::
Custom Search