10.5 Getting the Results


Now that we've seen how to create all sorts of useful dialog boxes, it's time to take a look at how to retrieve information about the user's interaction with the dialog. Table 10-7 showed the return types of the various methods. Here's a quick summary of what the returned values mean.

Input Dialogs

The versions that do not take an array of selection values return a String. This is the data entered by the user. The methods that do take an array of selection values return an Object reflecting the selected option. It's up to the L&F to determine the component used for presenting the options. Typically, a JComboBox is used if there are fewer than 20 choices, and a JList is used if there are 20 or more.[10] In any case, if the user presses the Cancel button, null is returned.

[10] Prior to SDK 1.4, the JList allowed the user to highlight multiple selections even though only the first could be detected. This has been fixed to allow only a single selection to be highlighted.

Confirm Dialogs

These methods return an int reflecting the button pressed by the user. The possible values are: YES_OPTION, NO_OPTION, CANCEL_OPTION, and OK_OPTION. CLOSED_OPTION is returned if the user closes the window without selecting anything.

Message Dialogs

These methods have void return types because they do not request a user response.

Option Dialogs

If no options are specified, this method returns one of the constant values YES_OPTION, NO_OPTION, CANCEL_OPTION, and OK_OPTION. If options are explicitly defined, the return value gives the index to the array of options that matches the button selected by the user. CLOSED_OPTION is returned if the user closes the window without selecting anything.

Getting a value from a JOptionPane you've instantiated directly is also very simple. The value is obtained by calling the pane's getValue( ) method. This method returns an Integer value using the same rules as those described for option dialogs with two small variations. Instead of returning an Integer containing CLOSED_OPTION, getValue( ) returns null if the dialog is closed. Also, if you call getValue( ) before the user has made a selection (or before displaying the dialog at all, for that matter), it will return UNINITIALIZED_VALUE. To get the value of user input (from a JTextField, JComboBox, or JList), call getInputValue( ). This will return the entered String or the selected Object (which may also be a String). Note that, just as with the static "show" methods, there's no way to find out about multiple selections the user may have made when there are more than 20 choices.

The following example contains code to retrieve results from JOptionPanes.



Java Swing
Graphic Java 2: Mastering the Jfc, By Geary, 3Rd Edition, Volume 2: Swing
ISBN: 0130796670
EAN: 2147483647
Year: 2001
Pages: 289
Authors: David Geary

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net