SWT uses the observer design pattern based event model.
Multiple listeners can be registered to be notified.
In SWT, only Widgets and Displays can have event listeners.
The following code demonstrates usage of a listener:
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class EventModelPattern {
static Display display = new Display();
public static void main(String[] args) {
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Button button = new Button(shell, SWT.PUSH);
button.setText("push me");
button.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
System.out.println("Button pushed.");
}
});
shell.open();
while (!shell.isDisposed()) { // Event loop.
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}