Where should I define a ButtonGroup and add the JToggleButtons (or JRadioButtons, JCheckboxes) to it?

Scott Stanchfield

Generally, you'll want to set up the ButtonGroup at the same time and in the same place as the buttons it controls.

For example, if you were defining three mutually-exclusive toggle buttons in a block you could set up the ButtonGroup there:


  JToggleButton b1 = new JToggleButton("A");
  JToggleButton b2 = new JToggleButton("B");
  JToggleButton b3 = new JToggleButton("C");

  ButtonGroup group = new ButtonGroup();
  group.add(b1);
  group.add(b2);
  group.add(b3);

Note that JCheckBox and JRadioButton are subclasses of JToggleButton, and you can use them in place of the JToggleButton above.

Another approach is to define a subclass of JPanel that does this automatically when toggle buttons are added. For example


  public class TogglePanel extends JPanel {
    private ButtonGroup group = new ButtonGroup();
    public void addImpl(Component comp,
                        Object constraint,
                        int index) {
      super.addImpl(comp, constraint, index);
      if (comp instanceof JToggleButton) {
        group.add((JToggleButton)comp);
      }
    }
    public void remove(Component comp) {
      super.remove(comp);
      group.remove(comp);
    }
    public void removeAll() {
      super.removeAll();
      group = new ButtonGroup();
    }
  }

Then, in the code that builds the GUI, you would use


  TogglePanel p = new TogglePanel();
  JToggleButton b1 = new JToggleButton("A");
  JToggleButton b2 = new JToggleButton("B");
  JToggleButton b3 = new JToggleButton("C");
  p.setLayout(new FlowLayout()); // perhaps...
  p.add(b1);
  p.add(b2);
  p.add(b3);
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact