如何在SWT中实现父子关系复选框?

时间:2018-07-24 12:28:06

标签: java checkbox swt

我是SWT的新手,我的要求是我需要在对话框中添加两个复选框。我想要,如果我选择了第一个复选框,则还应该选择第二个。 但是,如果我禁用第二个复选框,则第一个仍处于选中状态。我不允许选择第二个复选框,仅当选择第一个复选框时才选择第二个复选框。我相信必须使用其父子关系和CheckboxTreeViewer(仍然不确定)。有人可以跨要求发送代码片段吗?

1 个答案:

答案 0 :(得分:2)

Check out below code:

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

Output for above code

Step1 Step2 Step3 Step4 Step5