Java Reference
In-Depth Information
The JOptionPane Options and Initial Value Arguments
The
options
argument is an
Object
array used to construct a set of
JButton
objects for the
button area of the
JOptionPane
. If this argument is
null
(or a constructor without this argument
is used), the button labels will be determined by the
optionType
argument. Otherwise, the array
works similarly to the message argument, but without supporting recursive arrays:
•f an
options
array element is a
Component
, place the component in the button area.
•f an
options
array element is an
Icon
, place the
Icon
within a
JButton
and place the
button in the button area.
•f an
options
array element is an
Object
, convert it to a
String
with
toString()
, place the
String
in a
JButton
, and place the button in the button area.
Normally, the
options
argument will be an array of
String
objects. You may want to have
an
Icon
on the
JButton
, although the resulting button won't have a label. If you want to have
both an icon and a text label on the button, you can manually create a
JButton
and place it in
the array. Alternatively, you can directly include any other
Component
within the array. There's
one minor problem with these latter two approaches, however. It's
your
responsibility to
handle responding to component selection and tell the
JOptionPane
when the user selects this
component. The “Adding Components to the Button Area” section later in this chapter shows
how to properly handle this behavior.
When the
options
argument is non-
null
, the
initialValue
argument specifies which of
the buttons will be the default button when the pane is initially displayed. If it's
null
, the first
component in the button area will be the default button. In either case, the first button will
have the input focus, unless there is an input component in the message area, in which case,
the input component will have the initial input focus.
■
Tip
To have no buttons on the option pane, pass an empty array as the options setting:
new Object[] { }
.
Displaying a JOptionPane
After you've created the
JOptionPane
with one of the constructors, what you have is a panel
filled with components. In other words, the obtained
JOptionPane
is not yet in a pop-up window.
You need to create a
JDialog
, a
JInternalFrame
, or another pop-up window, and then place the
JOptionPane
within that. In addition, if you pick this manual style of
JOptionPane
construction,
you need to handle the closing of the pop-up window. You must listen for selection of a component
in the button area, and then hide the pop-up window after selection.
Because there is so much to do here, the
JOptionPane
includes two helper methods to
place a
JOptionPane
within either a modal
JDialog
or a
JInternalFrame
and take care of all the
previously described behavior: