【问题标题】:SWT: set radio buttons programmaticallySWT:以编程方式设置单选按钮
【发布时间】:2011-08-15 16:34:20
【问题描述】:

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

【问题讨论】:

    标签: radio-button swt radio-group


    【解决方案1】:

    不幸的是,您必须遍历所有选项。当您的 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 类了解更多详情。

    【讨论】:

      【解决方案2】:

      同一组合中的单选按钮将作为一个组。一次只能选择一个单选按钮。这是一个工作示例:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 即使它们在同一个父级上并且父级不是使用NO_RADIO_GROUP 创建的,它们仍然表现出问题中提到的行为。该行为至少在带有 eclipse 3.6 的 Windows Vista 上。如果它在其他操作系统或 eclipse 版本上工作,那么它是一个 SWT 错误
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 2015-05-30
        • 2012-02-24
        • 2014-09-20
        • 2014-09-03
        相关资源
        最近更新 更多