piątek, 9 kwietnia 2010

IHandler - How to obtain current selection based on ExecutionEvent object

The most common method of implementing custom handler is to subclass AbstractHandler. This very handy class reduce our work to fill just one method: execute(ExecutionEvent event). The entire stub looks as following:

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;

public class MyCustomHandler extends AbstractHandler {

 public Object execute(ExecutionEvent event) throws ExecutionException {
  // TODO Auto-generated method stub
  return null;

The question is how to obtain selection? Actually it is fairly simple and needs employ HandlerUtil class. This class is particularity interesting as delivers couple of utility method for working with ExecutionEvent object.

Two exemplary methods for obtaining current selection looks as below:

// the most straightforward ;>
ISelection selection = HandlerUtil.getCurrentSelection(event);

// and another more elaborate
ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();

ExecutionEvent javadoc:

The data object to pass to the command (and its handler) as it executes. This
carries information about the current state of the application, and the
application context in which the command was executed.

An execution event carries three blocks of data: the parameters, the trigger,
and the application context. How these blocks are used is application
dependent. In the Eclipse workbench, the trigger is an SWT event, and the
application context contains information about the selection and active part.


And someshing more about handlers: org.eclipse.ui.handlers

Brak komentarzy:

Prześlij komentarz