Check checkbox selection from within Listener

Keith Spriggs picture Keith Spriggs · Jan 18, 2013 · Viewed 19.1k times · Source

Working away at the moment but have come up with a small problem in JFace. I need to have a check box that allows the next button to become active.

Here is the code:

    Button btnConfirm = new Button(container, SWT.CHECK);

    btnConfirm.addSelectionListener(new SelectionAdapter() {
    @Override

    public void widgetSelected(SelectionEvent e) {

          //missing if statement        
          setPageComplete(true);
        }
    });

    btnConfirm.setBounds(330, 225, 75, 20);
    btnConfirm.setText("Confirm");

What I'm trying to do is to build a menu where someone has to accept the terms and conditions before they can progress beyond a point. The default is to be unchecked but, when the box is checked, the next button will appear; if it is not, then the next button will remain inactive.

Answer

Baz picture Baz · Jan 18, 2013

Just make the Button final and access it from within the Listener:

final Button btnConfirm = new Button(shell, SWT.CHECK);

btnConfirm.addSelectionListener(new SelectionAdapter()
{
    @Override
    public void widgetSelected(SelectionEvent e)
    {
        if (btnConfirm.getSelection())
            setPageComplete(true);
        else
            setPageComplete(false);
    }
});

Alternatively, get the Button from the SelectionEvent:

Button btnConfirm = new Button(shell, SWT.CHECK);

btnConfirm.addSelectionListener(new SelectionAdapter()
{
    @Override
    public void widgetSelected(SelectionEvent e)
    {
        Button button = (Button) e.widget;
        if (button.getSelection())
            setPageComplete(true);
        else
            setPageComplete(false);
    }
});