Java Reference
In-Depth Information
When you click the OK button, whatever you entered in the text field is returned by the
showInputDia-
log()
method and stored in
input
; this is
"This is the input..."
in this case. If you click the Cancel
button,
null
is returned. Note that this is not the same as
no
input. If you click OK without entering anything
in the text field, a reference to an empty
String
object is returned.
You could also use the overloaded version of the method that has the following form:
String showInputDialog(Component parent, Object message)
This version produces the same dialog as the previous method, but with the component you specify as
the first argument as the parent.
Another possibility is to use the method with the following form:
String showInputDialog(Component parent, Object message,
String title, int messageType)
In this case the title of the dialog is supplied by the third argument, and the style of the message is de-
termined by the fourth argument. The values for the fourth argument can be any of those I discussed earlier
in the context of message dialogs. For example, you could display the dialog shown in
Figure 20-6
with the
following statement:
String input = JOptionPane.showInputDialog(this, "Enter Input:",
"Dialog for Input",
JOptionPane.WARNING_MESSAGE);
Because of the fourth argument specification, the dialog displays a warning icon. The data that you enter
in the text field is returned by the
showInputDialog()
method when the OK button is pressed as before.
You also have a version that accepts seven arguments:
Object showInputDialog(Component parent, Object message,
String title, int messageType,
Icon icon, Object[] selections,
Object initialSelection)
This version of the method displays a dialog with a list of choices in a drop-down list box. You pass the
items that are the set of choices as the sixth argument to the method in the form of an array, and it can be
an array of elements of any class type. The initial selection to be shown when the dialog is first displayed
is specified by the seventh argument. Whatever is chosen when the OK button is clicked is returned as type
Object
, and if the Cancel button is clicked,
null
is returned. You can specify your own icon to replace the
default icon by passing a reference of type
Icon
as the fifth argument. The following statements display the
dialog shown in
Figure 20-7
: