SWT: set radio buttons programmatically
Asked Answered
L

3

7

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.

Lapp answered 29/4, 2011 at 18:2 Comment(0)
L
9

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.

Lynnette answered 29/4, 2011 at 22:56 Comment(0)
T
1

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");
Tryparsamide answered 17/9, 2013 at 13:35 Comment(0)
T
-2

This should happen automatically. How are you creating the buttons? Are they on the same parent? Is the parent using NO_RADIO_GROUP style?

Tintoretto answered 30/4, 2011 at 2:56 Comment(1)
Even if they are on the same parent and the parent is not created with NO_RADIO_GROUP, still they exhibit the behavior mentioned in the question. The behavior is at least on Windows Vista with eclipse 3.6. If its working on other OS or eclipse versions then its a SWT Bug.Lynnette

© 2022 - 2024 — McMap. All rights reserved.