SWT:以编程方式设置单选按钮

时间:2011-04-29 18:02:36

标签: radio-button swt radio-group

当我创建几个单选按钮(new Button(parent, SWT.RADIO))并使用radioButton5.setSelection(true)以编程方式设置选择时,之前选择的单选按钮也保持选中状态。我是否必须迭代同一组中的所有其他单选按钮以取消选择它们还是有更简单的替代方案?提前谢谢。

3 个答案:

答案 0 :(得分:7)

不幸的是,你必须遍历所有选项。当您的UI第一次出现时,会触发BN_CLICKED事件。如果您的ShellGroup或任何容器的单选按钮未使用SWT.NO_RADIO_GROUP选项创建,则会调用以下方法:

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);
}

因此,本质上eclipse本身取决于迭代所有单选按钮并切换其状态。

每次手动选择单选按钮时,BN_CLICKED事件都会被触发,因此会自动切换。

使用button.setSelection(boolean)时,不会触发BN_CLICKED个事件。因此,不会自动切换单选按钮。

查看org.eclipse.swt.widgets.Button课程了解更多详情。

答案 1 :(得分:1)

同一合成中的单选按钮将充当一个组。一次只能选择一个单选按钮。这是一个有效的例子:

    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");

答案 2 :(得分:-2)

这应该自动发生。你是如何创建按钮的?他们是同一个父母吗?父级是否使用NO_RADIO_GROUP样式?