SWT CheckBox Button get checked/unchecked state

saurabh picture saurabh · Oct 30, 2014 · Viewed 20.8k times · Source

I have a checkbox button based on which I want to set a variable as true or false. But I don't know how to handle the event. Here's my code:

Boolean check = false;
Button checkBox = new Button(composite,SWT.CHECK);
checkBox.setText("CheckBox");
checkBox.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent event) {
        if (event.detail == SWT.CHECK) {
            // Now what should I do here to get
            // Whether it is a checked event or unchecked event.
        }
    }
});

Answer

alex2410 picture alex2410 · Oct 30, 2014

To validate selection use getSource() method of event to get object(Button) and check is it selected:

    checkBox.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            Button btn = (Button) event.getSource();
            System.out.println(btn.getSelection());
        }
    });