Example usage for org.eclipse.jface.viewers IStructuredSelection getFirstElement

List of usage examples for org.eclipse.jface.viewers IStructuredSelection getFirstElement

Introduction

In this page you can find the example usage for org.eclipse.jface.viewers IStructuredSelection getFirstElement.

Prototype

public Object getFirstElement();

Source Link

Document

Returns the first element in this selection, or null if the selection is empty.

Usage

From source file:au.gov.ga.earthsci.discovery.ui.TableViewerSelectionHelper.java

License:Apache License

public TableViewerSelectionHelper(final TableViewer viewer, final Class<T> selectionType) {
    viewer.getControl().addMouseListener(new MouseAdapter() {
        @Override//from  w w w .j ava  2 s.  com
        public void mouseDown(MouseEvent e) {
            ViewerCell cell = viewer.getCell(new Point(e.x, e.y));
            if (cell == null) {
                viewer.setSelection(StructuredSelection.EMPTY);
            }
        }
    });

    viewer.getTable().addSelectionListener(new SelectionListener() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
            Object s = selection.getFirstElement();
            if (s == null) {
                itemSelected(null);
            } else if (selectionType.isInstance(s)) {
                T t = selectionType.cast(s);
                itemSelected(t);
            }
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
            Object s = selection.getFirstElement();
            if (selectionType.isInstance(s)) {
                T t = selectionType.cast(s);
                itemDefaultSelected(t);
            }
        }
    });
}

From source file:au.gov.ga.earthsci.layer.ui.LayerTreePart.java

License:Apache License

protected void createStructureViewer(Composite parent, EMenuService menuService, CTabItem tabItem) {
    structureViewer = new CheckboxTreeViewer(parent, SWT.MULTI);
    tabItem.setControl(structureViewer.getControl());
    structureViewer.getTree()//from   w w  w .  ja v a2 s  .c o  m
            .setBackgroundImage(ImageRegistry.getInstance().get(ImageRegistry.ICON_TRANSPARENT));
    context.set(TreeViewer.class, structureViewer);

    clipboard = new Clipboard(parent.getDisplay());
    context.set(Clipboard.class, clipboard);

    //create a property change listener for updating the labels whenever a property
    //changes on an ILayerTreeNode instance
    final PropertyChangeListener anyChangeListener = new PropertyChangeListener() {
        @Override
        public void propertyChange(final PropertyChangeEvent evt) {
            updateElementLabel(evt.getSource());
        }
    };
    //create a property change listener that ensures the expanded state of the tree
    //is kept in sync with the value of the expanded property for each node
    final PropertyChangeListener expandedChangeListener = new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            syncExpandedNodes();
        }
    };

    //setup the label provider
    labelProvider = new LayerTreeLabelProvider();

    //create a bean list property associated with ILayerTreeNode's children property
    IBeanListProperty<ILayerTreeNode, ILayerTreeNode> childrenProperty = BeanProperties
            .list(ILayerTreeNode.class, "children", ILayerTreeNode.class); //$NON-NLS-1$
    //setup a factory for creating observables observing ILayerTreeNodes
    IObservableFactory<ILayerTreeNode, IObservableList<ILayerTreeNode>> observableFactory = childrenProperty
            .listFactory();

    //listen for any changes (additions/removals) to any of the children in the tree
    observableListTreeSupport = new ObservableListTreeSupport<ILayerTreeNode>(observableFactory);
    observableListTreeSupport.addListener(new ITreeChangeListener<ILayerTreeNode>() {
        @Override
        public void elementAdded(ILayerTreeNode element) {
            element.addPropertyChangeListener(anyChangeListener);
            element.addPropertyChangeListener("expanded", expandedChangeListener); //$NON-NLS-1$
        }

        @Override
        public void elementRemoved(ILayerTreeNode element) {
            element.removePropertyChangeListener(anyChangeListener);
            element.removePropertyChangeListener("expanded", expandedChangeListener); //$NON-NLS-1$
        }
    });

    //create a content provider that listens for changes to any children in the tree
    ObservableListTreeContentProvider<ILayerTreeNode> contentProvider = new ObservableListTreeContentProvider<ILayerTreeNode>(
            observableFactory, null);

    //set the viewer's providers
    structureViewer.setContentProvider(contentProvider);
    structureViewer.setLabelProvider(labelProvider);
    structureViewer.setCheckStateProvider(new LayerTreeCheckStateProvider());

    //set the viewer and listener inputs
    structureViewer.setInput(model.getRootNode());
    observableListTreeSupport.setInput(model.getRootNode());

    //Listen for any additions to the tree, and expand added node's parent, so that
    //added nodes are always visible. This is done after the input is set up, so that
    //we don't expand all the nodes that are already in the tree.
    observableListTreeSupport.addListener(new TreeChangeAdapter<ILayerTreeNode>() {
        @Override
        public void elementAdded(ILayerTreeNode element) {
            //for any children added, expand the nodes
            if (!element.isRoot()) {
                element.getParent().setExpanded(true);
            }

            //if the nodes were already expanded, the expanded property change event
            //is not fired, so we need to sync the expanded state anyway
            syncExpandedNodes();

            //when a layer is added, we should activate this part and select the added element
            activateAndSelectElement(element);
        }
    });

    //expand any nodes that should be expanded after unpersisting
    syncExpandedNodes();

    //enable/disable any nodes that are checked/unchecked
    structureViewer.addCheckStateListener(new ICheckStateListener() {
        @Override
        public void checkStateChanged(CheckStateChangedEvent event) {
            Object element = event.getElement();
            if (element instanceof ILayerTreeNode) {
                ILayerTreeNode node = (ILayerTreeNode) element;
                node.enableChildren(event.getChecked());
            }
        }
    });

    //setup the selection tracking
    structureViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection selection = (IStructuredSelection) structureViewer.getSelection();
            List<?> list = selection.toList();
            ILayerTreeNode[] array = list.toArray(new ILayerTreeNode[list.size()]);
            settingSelection = true;
            selectionService.setSelection(array.length == 1 ? array[0] : array);
            settingSelection = false;
        }
    });
    structureViewer.getTree().addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            IStructuredSelection selection = (IStructuredSelection) structureViewer.getSelection();
            ILayerTreeNode firstElement = (ILayerTreeNode) selection.getFirstElement();
            if (firstElement != null) {
                selectLayer(firstElement);
            }
        }
    });

    //setup tree expansion/collapse listening
    structureViewer.addTreeListener(new ITreeViewerListener() {
        @Override
        public void treeExpanded(TreeExpansionEvent event) {
            ILayerTreeNode layerNode = (ILayerTreeNode) event.getElement();
            layerNode.setExpanded(true);
        }

        @Override
        public void treeCollapsed(TreeExpansionEvent event) {
            ILayerTreeNode layerNode = (ILayerTreeNode) event.getElement();
            layerNode.setExpanded(false);
        }
    });

    //make tree cells unselectable by selecting outside
    structureViewer.getTree().addMouseListener(new MouseAdapter() {
        @Override
        public void mouseDown(MouseEvent e) {
            ViewerCell cell = structureViewer.getCell(new Point(e.x, e.y));
            if (cell == null) {
                structureViewer.setSelection(StructuredSelection.EMPTY);
            }
        }
    });

    //setup cell editing
    structureViewer
            .setCellEditors(new CellEditor[] { new TextCellEditor(structureViewer.getTree(), SWT.BORDER) });
    structureViewer.setColumnProperties(new String[] { "layer" }); //$NON-NLS-1$
    structureViewer.setCellModifier(new ICellModifier() {
        @Override
        public void modify(Object element, String property, Object value) {
            if (element instanceof Item) {
                element = ((Item) element).getData();
            }
            ((ILayerTreeNode) element).setLabel((String) value);
        }

        @Override
        public Object getValue(Object element, String property) {
            if (element instanceof Item) {
                element = ((Item) element).getData();
            }
            return ((ILayerTreeNode) element).getLabelOrName();
        }

        @Override
        public boolean canModify(Object element, String property) {
            return true;
        }
    });

    ColumnViewerEditorActivationStrategy activationStrategy = new ColumnViewerEditorActivationStrategy(
            structureViewer) {
        @Override
        protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) {
            return event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
        }
    };
    TreeViewerEditor.create(structureViewer, activationStrategy, ColumnViewerEditor.KEYBOARD_ACTIVATION);

    //add drag and drop support
    int ops = DND.DROP_COPY | DND.DROP_MOVE;
    structureViewer.addDragSupport(ops,
            new Transfer[] { LocalLayerTransfer.getInstance(), LayerTransfer.getInstance() },
            new LayerTreeDragSourceListener(structureViewer));
    structureViewer
            .addDropSupport(ops,
                    new Transfer[] { LocalLayerTransfer.getInstance(), LayerTransfer.getInstance(),
                            FileTransfer.getInstance() },
                    new LayerTreeDropAdapter(structureViewer, model, context));

    //add context menu
    menuService.registerContextMenu(structureViewer.getTree(),
            "au.gov.ga.earthsci.application.layertree.popupmenu"); //$NON-NLS-1$
}

From source file:bndtools.editor.BndEditorContentOutlinePage.java

License:Open Source License

@Override
public void createControl(Composite parent) {
    super.createControl(parent);

    TreeViewer viewer = getTreeViewer();
    viewer.setAutoExpandLevel(2);//from w ww .j  a v  a2  s  .c o  m
    viewer.setContentProvider(new BndEditorContentOutlineProvider(viewer));
    viewer.setLabelProvider(new BndEditorContentOutlineLabelProvider());

    viewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            Object element = selection.getFirstElement();

            if (element instanceof String) {
                if (BndEditorContentOutlineProvider.EXPORTS.equals(element)) {
                    editor.setActivePage(BndEditor.CONTENT_PAGE);
                } else if (BndEditorContentOutlineProvider.IMPORT_PATTERNS.equals(element)) {
                    editor.setActivePage(BndEditor.CONTENT_PAGE);
                } else if (BndEditorContentOutlineProvider.PRIVATE_PKGS.equals(element)) {
                    editor.setActivePage(BndEditor.CONTENT_PAGE);
                } else if (BndEditorContentOutlineProvider.PLUGINS.equals(element)) {
                    editor.setActivePage(BndEditor.WORKSPACE_PAGE);
                } else {
                    editor.setActivePage((String) element);
                }
            } else if (element instanceof ExportedPackage) {
                BundleContentPage contentsPage = (BundleContentPage) editor
                        .setActivePage(BndEditor.CONTENT_PAGE);
                if (contentsPage != null) {
                    contentsPage.setSelectedExport((ExportedPackage) element);
                }
            } else if (element instanceof PrivatePkg) {
                BundleContentPage contentsPage = (BundleContentPage) editor
                        .setActivePage(BndEditor.CONTENT_PAGE);
                if (contentsPage != null) {
                    contentsPage.setSelectedPrivatePkg(((PrivatePkg) element).pkg);
                }
            } else if (element instanceof ImportPattern) {
                BundleContentPage contentsPage = (BundleContentPage) editor
                        .setActivePage(BndEditor.CONTENT_PAGE);
                if (contentsPage != null) {
                    contentsPage.setSelectedImport((ImportPattern) element);
                }
            } else if (element instanceof PluginClause) {
                WorkspacePage workspacePage = (WorkspacePage) editor.setActivePage(BndEditor.WORKSPACE_PAGE);
                if (workspacePage != null)
                    workspacePage.setSelectedPlugin(((PluginClause) element).header);
            }
        }
    });

    viewer.setInput(model);
}

From source file:bndtools.editor.pkgpatterns.PkgPatternsListPart.java

License:Open Source License

private void doInsertClausesAtSelection(Collection<? extends C> newClauses) {
    if (newClauses != null && !newClauses.isEmpty()) {
        int selectedIndex;
        IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
        if (selection.isEmpty())
            return;
        selectedIndex = this.clauses.indexOf(selection.getFirstElement());

        doAddClauses(newClauses, selectedIndex, true);
    }/*from   ww  w. j  a  v  a 2s  .  co  m*/
}

From source file:br.org.archimedes.gui.rca.InterpreterView.java

License:Open Source License

/**
 * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart,
 *      org.eclipse.jface.viewers.ISelection)
 *//*from w w w  . ja  v  a 2s.  co m*/
public void selectionChanged(IWorkbenchPart part, ISelection selection) {

    if (StructuredSelection.class.isAssignableFrom(selection.getClass())) {
        IStructuredSelection structuredSelection = (IStructuredSelection) selection;
        try {
            br.org.archimedes.Utils.getInputController()
                    .setDrawing((Drawing) structuredSelection.getFirstElement());
        } catch (ClassCastException e) {
            // This is a selection that does not regard drawings so I don't
            // care
        }
    }
}

From source file:br.ufal.cideei.handlers.DoAnalysisOnClassPath.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    //#ifdef CACHEPURGE
    //@      br.Main.randomLong();
    //#endif/*from  www  . j  a  va 2  s .  c o m*/

    // TODO: exteriorize this number as a configuration parameter. Abstract away the looping.
    try {
        IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveMenuSelection(event);
        Object firstElement = selection.getFirstElement();

        if (!(firstElement instanceof IJavaProject)) {
            throw new UnsupportedOperationException("Selected resource is not a java project");
        }

        IJavaProject javaProject = (IJavaProject) firstElement;

        IClasspathEntry[] classPathEntries = null;
        try {
            classPathEntries = javaProject.getResolvedClasspath(true);
        } catch (JavaModelException e) {
            e.printStackTrace();
            throw new ExecutionException("No source classpath identified");
        }

        /*
         * To build the path string variable that will represent Soot's classpath we will first iterate
         * through all libs (.jars) files, then through all source classpaths.
         * 
         * FIXME: WARNING: A bug was found on Soot, in which the FileSourceTag would contain incorrect
         * information regarding the absolute location of the source file. In this workaround, the classpath
         * must be injected into the FeatureModelInstrumentorTransformer class (done through its
         * constructor).
         * 
         * As a consequence, we CANNOT build an string with all classpaths that contains source code for the
         * project and thus one only source code classpath can be analysed at a given time.
         * 
         * This seriously restricts the range of projects that can be analysed with this tool.
         */
        List<IClasspathEntry> sourceClasspathEntries = new ArrayList<IClasspathEntry>();
        StringBuilder libsPaths = new StringBuilder();
        for (IClasspathEntry entry : classPathEntries) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                File file = entry.getPath().makeAbsolute().toFile();
                if (file.isAbsolute()) {
                    libsPaths.append(file.getAbsolutePath() + File.pathSeparator);
                } else {
                    libsPaths.append(ResourcesPlugin.getWorkspace().getRoot().getFile(entry.getPath())
                            .getLocation().toOSString() + File.pathSeparator);
                }
            } else if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                sourceClasspathEntries.add(entry);
            }
        }

        if (sourceClasspathEntries.size() != 1) {
            throw new UnsupportedOperationException("project must have exactly one source classpath entry");
        }

        IClasspathEntry entry = sourceClasspathEntries.get(0);

        final int times = 10;
        for (int i = 0; i < times; i++) {
            // #ifdef METRICS
            String sinkFile = System.getProperty("user.home") + File.separator
                    + javaProject.getElementName().trim().toLowerCase().replace(' ', '-') + "-fs";
            // #ifdef LAZY
            sinkFile += "-lazy";
            // #endif
            // #ifdef FEATUREMODEL
            //@                  sinkFile += "-fm";
            // #endif
            sink = new MetricsSink(new MetricsTable(new File(sinkFile + ".xls")));
            // #endif

            this.addPacks(javaProject, entry, libsPaths.toString());
            SootManager.reset();
            // #ifdef METRICS
            sink.terminate();
            // #endif
            System.out.println("=============" + (i + 1) + "/" + times + "=============");
        }
        sink.createSummaryFile();
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        SootManager.reset();
        // #ifdef METRICS
        if (sink != null && !sink.terminated()) {
            sink.terminate();
        }
        // #endif
    }

    return null;
}

From source file:br.ufal.cideei.handlers.DoFeatureObliviousAnalysisOnClassPath.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {/*from   w ww. j  a va  2  s.c  o  m*/
        IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveMenuSelection(event);
        Object firstElement = selection.getFirstElement();

        if (!(firstElement instanceof IJavaProject)) {
            throw new UnsupportedOperationException("selected resource is not a java project");
        }

        IJavaProject javaProject = (IJavaProject) firstElement;

        IClasspathEntry[] classPathEntries = null;
        try {
            classPathEntries = javaProject.getResolvedClasspath(true);
        } catch (JavaModelException e) {
            e.printStackTrace();
            throw new ExecutionException("No source classpath identified");
        }

        /*
         * To build the path string variable that will represent Soot's classpath we will first iterate
         * through all libs (.jars) files, then through all source classpaths.
         * 
         * FIXME: WARNING: A bug was found on Soot, in which the FileSourceTag would contain incorrect
         * information regarding the absolute location of the source file. In this workaround, the classpath
         * must be injected into the FeatureModelInstrumentorTransformer class (done though its
         * constructor).
         * 
         * As a consequence, we CANNOT build an string with all classpaths that contains source code for the
         * project and thus only one source code classpath can be analysed at a given time.
         * 
         * This seriously restricts the range of projects that can be analysed with this tool.
         */
        List<IClasspathEntry> sourceClasspathEntries = new ArrayList<IClasspathEntry>();
        StringBuilder libsPaths = new StringBuilder();
        for (IClasspathEntry entry : classPathEntries) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                File file = entry.getPath().makeAbsolute().toFile();
                if (file.isAbsolute()) {
                    libsPaths.append(file.getAbsolutePath() + File.pathSeparator);
                } else {
                    libsPaths.append(ResourcesPlugin.getWorkspace().getRoot().getFile(entry.getPath())
                            .getLocation().toOSString() + File.pathSeparator);
                }
            } else if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                sourceClasspathEntries.add(entry);
            }
        }

        if (sourceClasspathEntries.size() != 1) {
            throw new UnsupportedOperationException("project must have exactly one source classpath entry");
        }

        IClasspathEntry entry = sourceClasspathEntries.get(0);

        final int times = 10;
        for (int i = 0; i < times; i++) {
            // #ifdef METRICS
            String sinkFile = System.getProperty("user.home") + File.separator
                    + javaProject.getElementName().trim().toLowerCase().replace(' ', '-') + "-fo";
            // #ifdef LAZY
            sinkFile += "-lazy";
            // #endif
            // #ifdef FEATUREMODEL
            //@                  sinkFile += "-fm";
            // #endif
            sink = new MetricsSink(new MetricsTable(new File(sinkFile + ".xls")));
            // #endif

            this.addPacks(javaProject, entry, libsPaths.toString());
            SootManager.reset();
            // #ifdef METRICS
            sink.terminate();
            // #endif
            System.out.println("=============" + (i + 1) + "/" + times + "=============");
        }
        sink.createFeatureObliviousSummaryFile();
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        SootManager.reset();
        // #ifdef METRICS
        if (sink != null && !sink.terminated()) {
            sink.terminate();
        }
        // #endif
    }

    return null;
}

From source file:br.ufmg.dcc.tabuleta.actions.LoadConcernModelAction.java

License:Open Source License

/**
 * Whenever the selection changes, store the currently selected
 * file, if possible.//from  ww w . j av a2  s . co  m
 * @see IActionDelegate#selectionChanged(IAction, ISelection)
 * @param pAction the action proxy that handles presentation portion of 
  *       the action
  * @param pSelection the current selection, or <code>null</code> if there
  *       is no selection.
 */
public void selectionChanged(IAction pAction, ISelection pSelection) {
    IStructuredSelection lStructuredSelection = (IStructuredSelection) pSelection;
    Object lFile = lStructuredSelection.getFirstElement();
    if (lFile instanceof IFile) {
        aFile = (IFile) lFile;
    } else if (lFile instanceof IAdaptable) {
        Object lAdapter = ((IAdaptable) lFile).getAdapter(IResource.class);
        if (lAdapter instanceof IFile) {
            aFile = (IFile) lAdapter;
        }
    } else {
        aFile = null;
    }
}

From source file:br.ufscar.sas.ui.handlers.UI.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {

    // get workbench window
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    // set selection service
    ISelectionService service = window.getSelectionService();
    // set structured selection
    IStructuredSelection structured = (IStructuredSelection) service.getSelection();
    //Progress Monitor
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(window.getShell());
    //Reset Perspective
    window.getActivePage().resetPerspective();

    try {/*ww w  .jav  a2 s .co  m*/
        dialog.run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                //Creates KDM instance
                int totalUnitsOfWork = IProgressMonitor.UNKNOWN;
                monitor.beginTask("Performing Reverse Engineering....", totalUnitsOfWork);
                // Call Reverse Engineering
                String javaProjectName = "";
                String projectName = null;
                if (structured != null) {
                    if (structured.getFirstElement() instanceof IJavaProject) {
                        IJavaProject jProject = (IJavaProject) structured.getFirstElement();
                        projectName = jProject.getElementName();
                    }
                }

                javaProjectName = projectName;
                CreateKDM ck = new CreateKDM();
                ck.createKDMFile(javaProjectName);
                monitor.done();
                try {
                    refreshProjects();
                } catch (CoreException e) {
                    e.printStackTrace();
                }
            }
        });

        //Show main View
        window.getActivePage().showView("MainView");
        IWorkbenchPage ip = window.getActivePage();
        IViewPart myView = ip.findView("org.eclipse.jdt.ui.SourceView");
        ip.hideView(myView);
        myView = ip.findView("org.eclipse.jdt.ui.JavadocView");
        ip.hideView(myView);
        myView = ip.findView("org.eclipse.ui.views.ProblemView");
        ip.hideView(myView);
        myView = ip.findView("org.eclipse.mylyn.tasks.ui.views.tasks");
        ip.hideView(myView);
        myView = ip.findView("org.eclipse.ui.views.ContentOutline");
        ip.hideView(myView);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:c8_selectionservice.parts.SamplePart.java

License:Open Source License

@PostConstruct
public void createComposite(Composite parent) {
    parent.setLayout(new GridLayout(1, false));

    txtInput = new Text(parent, SWT.BORDER);
    txtInput.setMessage("Enter person name");
    txtInput.addModifyListener(new ModifyListener() {
        @Override//w  ww  .  j a  v a  2s.co  m
        public void modifyText(ModifyEvent e) {
            dirty.setDirty(true);
        }
    });
    txtInput.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    tableViewer = new TableViewer(parent);
    tableViewer.setLabelProvider(new LabelProvider() {
        @Override
        public String getText(Object element) {
            if (element instanceof Person) {
                return ((Person) element).getName();
            }
            return "invalid object";
        }
    });
    tableViewer.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
    tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            selectionService.setSelection(selection.getFirstElement());
        }
    });
    initData(tableViewer);
}