How to get a set of buttons (JButton's) to work together as a group

By Alvin J. Alexander, devdaily.com

Here's a very simple example of how to create and use a button group in Java using the ButtonGroup class. With this code, when the user selects one JButton in the group of buttons, the other JButton's will be de-selected.

The code itself seems pretty much self-explanatory. Just create a ButtonGroup, then add the desired buttons to the group. I suppose the only thing I will say about the code is that I generated most of it with JBuilder X, so that's why there is a crazy jbInit() method plopped in the middle of it.

With no furtho ado, here is the code:

package poop;

import java.awt.*;
import javax.swing.*;

public class PoopButtonPanel extends JPanel {
  BorderLayout borderLayout1 = new BorderLayout();
  JPanel jPanel1 = new JPanel();
  JRadioButton button1 = new JRadioButton();
  JRadioButton button2 = new JRadioButton();
  JRadioButton button3 = new JRadioButton();
  ButtonGroup buttons = new ButtonGroup();

  public PoopButtonPanel() {
    try {
      jbInit();
    }
    catch(Exception ex) {
      ex.printStackTrace();
    }
  }

  void jbInit() throws Exception {
    this.setLayout(borderLayout1);
    jPanel1.setLayout(null);
    button1.setText("Button 1");
    button1.setBounds(new Rectangle(132, 75, 91, 23));
    button2.setText("Button 2");
    button2.setBounds(new Rectangle(132, 100, 91, 23));
    button3.setText("Button 3");
    button3.setBounds(new Rectangle(132, 124, 91, 23));
    this.add(jPanel1, BorderLayout.CENTER);
    jPanel1.add(button1, null);
    jPanel1.add(button2, null);
    jPanel1.add(button3, null);
    
    // this is where the radio buttons are added to the button group
    buttons.add(button1);
    buttons.add(button2);
    buttons.add(button3);
  }
}

 


devdaily logo