SWT: set radio buttons programmatically

Mot picture Mot · Apr 29, 2011 · Viewed 8.3k times · Source

When I create a couple of radio buttons (new Button(parent, SWT.RADIO)) and set the selection programmatically using radioButton5.setSelection(true) the previously selected radio button also remains selected. Do I have to iterate over all other radio buttons of the same group to unselect them or is there a simpler alternative? Thanks in advance.

Answer

Favonius picture Favonius · Apr 30, 2011

Unfortunately, you have to iterate over all the options. For the first time when your UI comes up then a BN_CLICKED event is fired. If your Shell or Group or whatever container of radio buttons is not created with SWT.NO_RADIO_GROUP option then the following method is called:

void selectRadio () 
{
    Control [] children = parent._getChildren ();
    for (int i=0; i<children.length; i++) {
        Control child = children [i];
        if (this != child) child.setRadioSelection (false);
    }
    setSelection (true);
}

So essentially eclipse itself depends on iterating over all the radio buttons and toggling their state.

Every time you manually select a Radio Button the BN_CLICKED event is fired and hence the auto toggling.

When you use button.setSelection(boolean) then no BN_CLICKED event is fired. Therefore no automatic toggling of radio buttons.

Check the org.eclipse.swt.widgets.Button class for more details.