【问题标题】:How to implement parent child relationship checkbox in SWT?如何在 SWT 中实现父子关系复选框?
【发布时间】:2018-10-04 11:51:44
【问题描述】:

我是 SWT 新手,我的要求是我需要在对话框中添加两个复选框。我想,如果我选择第一个复选框,第二个也应该被选中。 但如果我禁用第二个复选框,第一个仍被选中。我不允许选择第二个复选框,只有在选中第一个复选框时才会选择第二个复选框。我相信它是父子关系,必须使用 CheckboxTreeViewer(仍然不确定)。任何人都可以通过代码 sn-p 发送要求吗?

【问题讨论】:

  • 您要问的内容非常广泛。你试过什么了?你能提供一个Minimal, Complete, and Verifiable example吗?
  • 两个普通的 SWT.CHECK 按钮对于强制执行条件的选择侦听器应该没问题。我不认为 CheckboxTreeViewer 真的有帮助。

标签: java checkbox swt


【解决方案1】:

查看以下代码:

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

public class CheckBoxExample {
    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new GridLayout(3, true));

        Button parentButton = new Button(shell, SWT.CHECK);
        parentButton.setText("Parent");
        Button childButton = new Button(shell, SWT.CHECK);
        childButton.setText("Child");
        childButton.setEnabled(false);

        parentButton.addListener(SWT.Selection, event -> {
            if (!parentButton.getSelection()) {
                childButton.setEnabled(false);
                childButton.setSelection(false);
                return;
            }
            childButton.setEnabled(true);
        });

        shell.pack();
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }
}

以上代码的输出

【讨论】:

  • 嗨,Shashwat,评论很晚,但已经实现了您建议的代码。它工作正常,但我面临一个问题。根据您的代码,一旦对话框第一次加载,childButton 就会显示为启用。当我选择 parentButton 然后再次取消选中 parentButton 时,它显示禁用。但是我想在第一次加载对话框时显示 childButton 显示为灰色。您能否建议解决方法?
  • 如果它适合您的用例,您可以签出setGrayed() 方法
  • 感谢您的 cmets。我尝试了两件事 1)将 parentButton 设置为 final,默认情况下它确实显示 childButton 为非活动状态。我选择 parentButton 并且 childButton 也被选中(根据需要)。但现在我无法取消选中 childButton。尽管我的要求是我可以检查/取消选中的孩子(只有在检查ParentButton的情况下)。 2)正如你所建议的,我在 if (!parentButton.getSelection()) { childButton.setGrayed(true);childButton.setSelection(false);return } 中做了 setGrayed(true) 。并且 childButton 现在被阻止。无法执行任何操作。请建议
  • 我无法理解您的要求,所以请对您的工作代码提出质疑。正如您所说的:“尽管我的要求是我可以检查/取消选中的孩子(只有在检查父母键盘时)。这意味着应该禁用孩子按钮,而不是灰色
猜你喜欢
  • 1970-01-01
  • 2013-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多