Java Reference
In-Depth Information
When you run this example, you'll see the screen shown in Figure 5-11.
Figure 5-11. Grouping JRadioButton components with the RadioButtonUtils helper class
Note If you're familiar with the standard AWT library, the JRadioButton / ButtonGroup combination
works exactly like the Checkbox / CheckboxGroup pair.
Handling JRadioButton Selection Events
Like JToggleButton and JCheckBox , JRadioButton supports the registration of an ActionListener ,
an ItemListener , and a ChangeListener . And again, their usage with JRadioButton is somewhat
different than with the other components.
Listening to JRadioButton Events with an ActionListener
With a JRadioButton , it's common to attach the same ActionListener to all the radio buttons in
a ButtonGroup . That way, when one of the radio buttons is selected, the subscribed ActionListener
will be notified. By overloading the earlier createRadioButtonGrouping() method, the method
can accept an ActionListener argument and attach the listener object to each of the buttons as
they're created.
public static Container createRadioButtonGrouping (String elements[], String title,
ActionListener actionListener) {
JPanel panel = new JPanel(new GridLayout(0, 1));
// If title set, create titled border
if (title != null) {
Border border = BorderFactory.createTitledBorder(title);
panel.setBorder(border);
}
// Create group
ButtonGroup group = new ButtonGroup();
JRadioButton aRadioButton;
// For each String passed in:
// Create button, add to panel, and add to group
 
Search WWH ::




Custom Search