By Alvin Alexander. Last updated: June 4, 2016
Here's a very simple Java JButton example that shows 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 Java 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 an extra jbInit() method plopped in the middle of it.
With no further ado, here is my example Java/JButton/ButtonGroup code:
import java.awt.*; import javax.swing.*; public class JavaButtonGroupExamplePanel 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 JavaButtonGroupExamplePanel() { 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); } }