Responding to Button Clicks

A button is useless unless you provide some mechanism that responds to the user having clicked the button. To do that, you must add a SelectionListener to the button and develop code in the widgetSelected( ) event to accomplish the desired task.

How do I do that?

To respond to the button being clicked by the user, you need to add a SelectionListener to the code shown in Example 6-1:

               import org.eclipse.swt.events.*;

//then, in the constructor of ButtonExample
b1.addSelectionListener(new SelectionAdapter( ) {
   public void widgetSelected(SelectionEvent e) {
         System.out.println("Push Me Was Pushed");
   }
});

This code performs the task of printing to the Console when the button is clicked. This is essentially all you need to know about SWT.PUSH -style buttons and how to use them to permit the user to initiate some action. Whatever action you wish your button to perform, the steps required to develop the code will be the same.

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.