How do I group a set of radio buttons with a nice border and title?
Created May 7, 2012
You can use a Swing Border to draw a decorative titled border around the group of radio buttons.
The main "trick" here is to place the buttons you want to group in a JPanel by themselves, then add a Border to the JPanel.
The following code shows a simple example of doing this.
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import java.awt.FlowLayout;
import java.awt.GridLayout;
public class Sample2 {
public static void main(String[] args) {
new Sample2().go();
}
public void go() {
JFrame f = new JFrame("Sample");
JPanel p = new JPanel(new GridLayout(0,1,3,3));
p.setBorder(BorderFactory.createTitledBorder("Age group"));
JRadioButton b1 = new JRadioButton("< 6");
JRadioButton b2 = new JRadioButton("7-13");
JRadioButton b3 = new JRadioButton("14-20");
JRadioButton b4 = new JRadioButton("21-35");
JRadioButton b5 = new JRadioButton("36-62");
JRadioButton b6 = new JRadioButton("> 62");
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
p.add(b5);
p.add(b6);
ButtonGroup group = new ButtonGroup();
group.add(b1);
group.add(b2);
group.add(b3);
group.add(b4);
group.add(b5);
group.add(b6);
f.getContentPane().setLayout(new FlowLayout());
f.getContentPane().add(p);
f.pack();
f.setVisible(true);
}
}