Adding Listeners to CHECK Buttons

On a few occasions it will be necessary to add a Listener to an SWT.CHECK-style button. One instance when this is required is when you want to populate a List or Combo with items depend on which button is checked.

How do I do that?

The following code adds a SelectionListener to the SWT.CHECK buttons created in the section “Creating Check Buttons” and, in the widgetSelected() method, determines the state of the button at the time the button is clicked:

b1.addSelectionListener(new SelectionAdapter( ) {
    public void widgetSelected(SelectionEvent e) {
        System.out.println(b1.getSelection( ));
    }
});
b2.addSelectionListener(new SelectionAdapter( ) {
    public void widgetSelected(SelectionEvent e) {
        System.out.println(b2.getSelection( ));
    }
});

In the widgetSelected( ) method of these Listeners, determine the selection state of the button, then take any action required based on that state. This code will be executed each time the button’s state changes.

Get SWT: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.