SWT tip: Using SelectionAdapter

This one is probably for newbies.

When providing a SelectionListener for doing a something when a SWT button is pressed, you’ll need to implement two methods:


Button b = new Button(container, SWT.PUSH);
b.addSelectionListener( new SelectionListener()
{
  public void widgetSelected( SelectionEvent e )
  {
    // TODO Auto-generated method stub
  }

  public void widgetDefaultSelected( SelectionEvent e )
  {
    // TODO Auto-generated method stub
  }
} );

However, only one of those methods will be called: widgetSelected

So you can save a couple of lines (which is always nice, specially when inlining the handlers like in these examples) by using SelectionAdapter, an implementation of SelectionListener with default implementation of both methods (which is to do nothing).

The final, shorter, core looks like this:


Button b = new Button(container, SWT.PUSH);
b.addSelectionListener( new SelectionAdapter()
{
  public void widgetSelected( SelectionEvent e )
  {
    doSomething();
  }
} );


  1. I just recently figured this out myself! I had actually used SelectionAdapter from sample code, just never bothered to look close enough at the code I wasn’t tweaking.






%d bloggers like this: