Java Reference
In-Depth Information
method. As a result, there's no direct route to find out which
JRadioButton
object (or objects) is
selected within the
ButtonGroup
of the returned container. This may be necessary, for example,
if there were an Order Pizza button on the screen and you wanted to find out which pizza-order
options were selected after the user clicked that button.
The following helper method,
public Enumeration getSelectedElements(Container
container)
, when added to the previously created
RadioButtonUtils
class (Listing 5-5), will
provide the necessary answer. The helper method will work only if the container passed into
the method is full of
AbstractButton
objects. This is true for those containers created with the
previously described
createRadioButtonGrouping()
methods, although the
getSelectedElements()
method can be used separately.
public static Enumeration<String> getSelectedElements(Container container) {
Vector<String> selections = new Vector<String>();
Component components[] = container.getComponents();
for (int i=0, n=components.length; i<n; i++) {
if (components[i] instanceof AbstractButton) {
AbstractButton button = (AbstractButton)components[i];
if (button.isSelected()) {
selections.addElement(button.getText());
}
}
}
return selections.elements();
}
To use the
getSelectedElements()
method, you just need to pass the container returned
from
createRadioButtonGrouping()
to the
getSelectedElements()
method to get an
Enumeration
of
the selected items as
String
objects. The following example demonstrates this.
final Container crustContainer =
RadioButtonUtils.createRadioButtonGrouping(crustOptions, "Crust Type");
ActionListener buttonActionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Enumeration selected = RadioButtonUtils.getSelectedElements(crustContainer);
while (selected.hasMoreElements()) {
System.out.println ("Selected -> " + selected.nextElement());
}
}
};
JButton button = new JButton ("Order Pizza");
button.addActionListener(buttonActionListener);
It may be necessary for
getSelectedElements()
to return more than one value, because if
the same
ButtonModel
is shared by multiple buttons in the container, multiple components of the
ButtonGroup
will be selected. Sharing a
ButtonModel
between components isn't the norm. If
you're sure your button model won't be shared, then you may want to provide a similar
method that returns only a
String
.