简体   繁体   中英

How to implement parent child relationship checkbox in SWT?

I am new to SWT, my requirement is I need to add two checkboxes in a dialog. I want, if I select first checkbox second should also be selected. But if I am disabling second checkbox , first one is still selected. I am not allowed to select second checkbox, second checkbox is only selected when first checkbox is selected. I believe its a parent child relationship and CheckboxTreeViewer must be used(still not sure). Can anyone please send across code snippet for the requirement?

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

第1步 第2步 第三步 第四步 步骤5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM