Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWT: set radio buttons programmatically

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.

like image 283
Mot Avatar asked Apr 29 '11 18:04

Mot


2 Answers

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.

like image 151
Favonius Avatar answered Dec 15 '22 05:12

Favonius


The radio buttons within the same composite would act as a group. Only one radio button will be selected at a time. Here is a working example:

    Composite composite = new Composite(parent, SWT.NONE);

    Button btnCopy = new Button(composite, SWT.RADIO);
    btnCopy.setText("Copy Element");
    btnCopy.setSelection(false);

    Button btnMove = new Button(composite, SWT.RADIO);
    btnMove.setText("Move Element");
like image 23
sudipn Avatar answered Dec 15 '22 05:12

sudipn