Java Reference
In-Depth Information
for (int i=0, n=elements.length; i<n; i++) {
aRadioButton = new JRadioButton (elements[i]);
panel.add(aRadioButton);
group.add(aRadioButton);
if (actionListener != null) {
aRadioButton.addActionListener(actionListener);
}
}
return panel;
}
Now if a group is created with the following source, the same ActionListener will be notified
for each of the JRadioButton components created. Here, the listener prints out only the currently
selected value. How you choose to respond may vary.
ActionListener sliceActionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton aButton = (AbstractButton)actionEvent.getSource();
System.out.println("Selected: " + aButton.getText());
}
};
Container sliceContainer =
RadioButtonUtils.createRadioButtonGrouping(sliceOptions, "Slice Count",
sliceActionListener);
However, note that there are two problems with this approach. First, if a JRadioButton is
already selected and then selected again, any attached ActionListener objects will still be notified
once more. Although you cannot stop the double notification of subscribed ActionListener
objects, with a little work, you can handle it properly. You need to retain a reference to the last
selected item and check for reselection. The following modified ActionListener checks for this:
ActionListener crustActionListener = new ActionListener() {
String lastSelected;
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton aButton = (AbstractButton)actionEvent.getSource();
String label = aButton.getText();
String msgStart;
if (label.equals(lastSelected)) {
msgStart = "Reselected: ";
} else {
msgStart = "Selected: ";
}
lastSelected = label;
System.out.println(msgStart + label);
}
};
The second problem has to do with determining which JRadioButton is selected at any
given time. With the overloaded RadioButtonUtils.createRadioButtonGrouping() helper methods,
neither the ButtonGroup nor the individual JRadioButton components are visible outside the
Search WWH ::




Custom Search