Selection Providers and Listeners

The JLense workbench has some simple yet sophisticated mechanisms for tracking selected items in the workbench and for listening to selection changes.
When you understand how these selection mechanisms work you will understand how to make GUI elements in the JLense Workbench respond to selection changes. For instance, you will understand how make the Open action become enabled when the selected objected is openable, or the Print action become enabled when the current item is printable.

Discovering the Current Selection

The JLense Workbench tracks the current selection and the current selection can always be discovered by a plugin or a view or whatever as shown below:

IWorkbench workbench= PlatformUI.getWorkbench();
IWindowManager windowManager= workbench.getWindowManager();
IWorkbenchWindow activeWindow= windowManager.getActiveWindow();
ISelection selection= activeWindow.getSelectionService().getSelection();

Iterator selectionIterator= selection.iterator();
while (selectionIterator.hasNext()) {
    Object selectedObject= selectionIterator.next();
}

The JLense Workbench tracks the current selection by tracking the active window. Every workbench window has a 'Selection Service' that can supply the current selection within the window as an ISelection.

Views and ISelectionProviders

In the code in the previous section the active window's selection service can provide the caller with the current selection. But how does the window know what's selected? The answer is that each view in a window provides the window with an ISelectionProvider that can tell the window what is selected in the view.

Views provide the workbench with an ISelectionProvider by setting the selection provider on the view's associated site object when the view's UI component is created. The snippet of code below shows how a typical view exports it's selection provider to the rest of the world.

/**
 * A view that displays a list of Accounts.
 */
public class AccountsView extends OutlookPart
{
    /* 
     * Method declared on IWorkbenchPart
     */
    public JComponent createPartControl()
    {
        /*
        Create a widget that will represent this view in Workbench GUI.
        Support for ISelectionProvider is built into this widget.
        */
        AccountListJPanel accountsListPanel = new AccountListJPanel();

        /*
        Set the selection provider for this part's site to a selection 
        provider that provides access to accounts.
        */
        getSite().setSelectionProvider(accountsPanel.getSelectionProvider());
    }
}