(For an overview of the G$D/Groovy series, see <http://www.oreillynet.com/pub/wlg/5789>.)

Radio buttons and SwingBuilder

This one is short and sweet. To make radio buttons in Swing, you instantiate a set of JRadioButtons and add them to a ButtonGroup. Only one button in a ButtonGroup will be allowed to be selected at a time.

You might think SwingBuilder would provide a buttonGroup() method that would allow you to contain radio buttons, but you’d be wrong:


import groovy.swing.SwingBuilder;
import java.awt.FlowLayout;

swing = new SwingBuilder();
gui = swing.frame(size:[250,100]) {
    panel(layout:new FlowLayout()) {
        // WARNING: This code won't work!
        buttonGroup() {
            radioButton(text:"One");
            radioButton(text:"Two");
            radioButton(text:"Three");
        } 
    }
}

gui.show();

There is a buttonGroup() method in SwingBuilder, but you can’t use it as a container. Instead, you have to create the ButtonGroup (using SwingBuilder’s buttonGroup() method) and hold it in a variable, and add it to the radio buttons as a property:


import groovy.swing.SwingBuilder;
import java.awt.FlowLayout;

swing = new SwingBuilder();
gui = swing.frame(size:[250,100]) {
    panel(layout:new FlowLayout()) {
        // This will work:
        myGroup = buttonGroup();
        radioButton(text:"One", buttonGroup:myGroup);
        radioButton(text:"Two", buttonGroup:myGroup, selected:true);
        radioButton(text:"Three", buttonGroup:myGroup);
    }
}

gui.show();

Here’s the result:

image