Learning starts with a question and continues with a discovery Stay hungry for knowledge.
Learning starts with a question and continues with a discovery Stay hungry for knowledge.
Learning starts with a question and continues with a discovery Stay hungry for knowledge.
Learning starts with a question and continues with a discovery Stay hungry for knowledge.
Before Java5 it was common to use option panes for keyboard input because buffered readers are so awkward to use. The idea in that particular example is that opening the dialogue window starts the event dispatch thread (??) (=EDT), and terminating the main method terminates the main thread. That may leave the EDT running, so you need System.exit to terminate all threads.Horstmann and Cornell, page 60 wrote:NOTE: If you do not have JDK5.0 or above, you will have to work harder to read user input. The simplest method is to use an input dialog (see figure 3-6).
String input = JOptionpane.showInputDialog(promptString)
The return value is the strin g that the user typed.
For example, this is how you can query the name of the user of your program:
String name = JOptionPane.showInputDialog("What is your name?");
Reading numbers requires an additional step. The JOptionPane.showInputDialog method returns a string, not a number. You use the Integer.parseInt or Double.parseDouble method to convert the string to its numeric value. For example,
String input = JOptionPane.showInputDialog("How old are you?");
int age = Integer.parseInt(input);
If the user types 45, then the string variable input is set to the string "45". The Integer.parseInt method converts the string to its numeric value, the number 45.
The JOptionPane class is defined in the javax.swing package, so you need to add the statement
import javax.swing.*;
Finally, whenever your program calls JOptionPane,showInputDialog, you need to end it with a call to System.exit(0). The reason is a bit technical. Showing a dialog box starts a new thread of control. When the main mathod exits, the new thread does not autoatically terminate. To end all threads, you call the System.exit method. (For more information on threads, see Chapter 1 of Volume 2.) The following program is the equivalent of Example 3-2 prior to JDK5.0.
Campbell Ritchie wrote:1: This is something you had to do in JDK1.4 and it is no longer necessary because you usually use Scanner for keyboard input.
Learning starts with a question and continues with a discovery Stay hungry for knowledge.
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |