Making Menus Perform the Intended Action

Of course, if you click any of the menu items in the MenuShell example, nothing happens. You must complete one more task to make your menu items perform their intended function—you must attach a Listener to your menu items. As the name implies, a Listener listens for a particular event to occur and then takes some action upon the occurrence.

A Listener is a class that extends one of the Listener interfaces. When an event occurs, the event loop for the main shell of the application dispatches that event to be handled by the Listener attached to the widget that is causing the event to occur. The result is that one of the methods of the Listener will be called. It is in those methods that you develop the code that executes when the event occurs.

The SWT provides you with several Listener interfaces, all a part of the org.eclipse.swt.events or org.eclipse.swt.widgets packages. To use a Listener, first identify the type of event that you are listening for, then call a method to attach that Listener to the widget. Finally, add code to the listener’s methods to perform the desired task.

How do I do that?

To add a SelectionListener to the MenuItem childItem in MenuExample, use the following code:

childItem.addSelectionListener(new SelectionListener( ) { public void widgetSelected(SelectionEvent e) { Shell parent = (Shell)maxItem.getParent( ).getParent( ); ChildShell cs = new ChildShell(parent); } public void widgetDefaultSelected(SelectionEvent e) ...

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.