Java Reference
In-Depth Information
The basic formats for a JOptionPane dialog box fall into three categories. A
message dialog box simply displays an output string. An input dialog box presents
a prompt and a single input text field into which the user can enter one string of
data. A confirm dialog box presents the user with a simple yes-or-no question.
Let's look at a program that uses each of these types of dialog boxes. Listing 6.9
shows a program that first presents the user with an input dialog box that requests
the user to enter an integer. After the user presses the OK button on the input dialog
box, a second dialog box (this time a message dialog box) appears, informing the
user whether the number entered was even or odd. After the user dismisses that
box, a third dialog box appears, to determine whether the user would like to test
another number. If the user presses the button labeled Yes , the series of dialog
boxes repeats. Otherwise the program terminates.
LISTING 6.9
//********************************************************************
// EvenOdd.java Author: Lewis/Loftus
//
// Demonstrates the use of the JOptionPane class.
//********************************************************************
import javax.swing.JOptionPane;
public class EvenOdd
{
//-----------------------------------------------------------------
// Determines if the value input by the user is even or odd.
// Uses multiple dialog boxes for user interaction.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String numStr, result;
int num, again;
do
{
numStr = JOptionPane.showInputDialog ("Enter an integer: ");
num = Integer.parseInt(numStr);
result = "That number is " + ((num%2 == 0) ? "even" : "odd");
JOptionPane.showMessageDialog ( null , result);
again = JOptionPane.showConfirmDialog ( null , "Do Another?");
}
while (again == JOptionPane.YES_OPTION);
 
Search WWH ::




Custom Search