Next: Example: initials of a
Up: Unit 02
Previous: Example: initials of a
An alternative way to read strings from input is to use the predefined method
showInputDialog(), which is defined in the class JOptionPane,
which in turn is part of the swing library. Using such a method, we
can read input from the keyboard according to the following schema:
import javax.swing.JOptionPane;
public class KeyboardInput {
public static void main (String[] args) {
...
String inputString = JOptionPane.showInputDialog("Insert a string");
...
System.out.println(inputString);
...
System.exit(0);
}
}
- import javax.swing.JOptionPane; - imports the class
JOptionPane from the library javax.swing
- String inputString = JOptionPane.showInputDialog("Insert a
string");
- creates a dialog window (see figure) showing the message
"Insert a string",
- reads a string from the keyboard,
- returns (a reference to) such a string, and
- assigns the reference to the variable inputString.
- System.exit(0); must be added to the main() method when
the predefined library class JOptionPane is used - this is
necessary, since dialog windows are not handled directly by main(),
and hence we have to provide an explicit command to terminate them.
Next: Example: initials of a
Up: Unit 02
Previous: Example: initials of a