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:cn.dockerfoundry.ide.eclipse.explorer.ui.views.DockerImagesView.java

License:Open Source License

private void fillContextMenu(IMenuManager manager) {
    if (viewer.getSelection() instanceof IStructuredSelection) {
        IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
        if (selection.size() < 1)
            return;
        Object obj = selection.getFirstElement();
        System.out.println(obj);/* w  ww. java 2  s.  co  m*/
        if (obj instanceof DockerImageElement) {
            DockerImageElement elem = (DockerImageElement) obj;
        }
    }
    manager.add(pullImageAction);
    manager.add(pushmageAction);
    manager.add(createImageAction);
    manager.add(createContainerAction);
    manager.add(deleteImageAction);
    manager.add(inspectAction);
    manager.add(refreshAction);

    // Other plug-ins can contribute there actions here
    manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}

From source file:cn.dockerfoundry.ide.eclipse.server.ui.internal.actions.MenuActionHandler.java

License:Open Source License

/**
 * Returns a list of applicable context menu actions based on the given
 * context. Always returns a non-null list, although the list may be empty
 * if no actions are applicable to the given context.
 * //from  www .  jav  a 2 s . c om
 * @param context to evaluate for the creation of actions. If null, an
 * attempt will be made to obtain the context directly from the Servers view
 * @return non-null list of actions corresponding to the given evaluation
 * context. May be empty if context is invalid.
 */
@SuppressWarnings("unchecked")
protected T getSelectionFromContext(Object context) {
    T selection = null;

    // First check if the context is an evaluation context, and attempt to
    // obtain the server module from the context
    if (context instanceof IEvaluationContext) {

        Object evalContext = ((IEvaluationContext) context).getDefaultVariable();

        if (evalContext instanceof List<?>) {
            List<?> content = (List<?>) evalContext;
            if (!content.isEmpty()) {
                Object obj = content.get(0);
                if (selectionClass.isAssignableFrom(obj.getClass())) {
                    selection = (T) obj;
                }
            }
        }
    }

    // Failed to get context selection from context.
    // Try the servers view directly
    if (selection == null) {

        IStructuredSelection strucSelection = CloudUiUtil.getServersViewSelection();
        if (strucSelection != null && !strucSelection.isEmpty()) {
            Object selectObj = strucSelection.getFirstElement();
            if (selectionClass.isAssignableFrom(selectObj.getClass())) {
                selection = (T) selectObj;
            }
        }
    }

    return selection;
}

From source file:cn.dockerfoundry.ide.eclipse.server.ui.internal.editor.ApplicationDetailsPart.java

License:Open Source License

public void selectionChanged(IFormPart part, ISelection selection) {
    IStructuredSelection sel = (IStructuredSelection) selection;
    module = (IModule) sel.getFirstElement();

    refreshUI();/*from  w  w  w .  j ava2s . c  om*/
    editorPage.refresh(RefreshArea.DETAIL);
}

From source file:cn.dockerfoundry.ide.eclipse.server.ui.internal.editor.ApplicationMasterPart.java

License:Open Source License

private void createApplicationsSection() {
    Section section = getSection();/*from  w w w.  ja  v a2  s.c om*/
    section.setLayout(new GridLayout());
    GridDataFactory.fillDefaults().grab(true, true).applyTo(section);
    section.setText(Messages.COMMONTXT_APPLICATIONS);
    section.setDescription(Messages.ApplicationMasterPart_TEXT_APP_DESCRIP);

    Composite client = toolkit.createComposite(section);
    client.setLayout(new GridLayout());
    GridDataFactory.fillDefaults().grab(true, true).applyTo(client);
    section.setClient(client);

    Composite headerComposite = toolkit.createComposite(section, SWT.NONE);
    RowLayout rowLayout = new RowLayout();
    rowLayout.marginTop = 0;
    rowLayout.marginBottom = 0;
    headerComposite.setLayout(rowLayout);
    headerComposite.setBackground(null);

    ToolBarManager toolBarManager = new ToolBarManager(SWT.FLAT);
    toolBarManager.createControl(headerComposite);

    applicationsViewer = new TableViewer(toolkit.createTable(client, SWT.NONE));
    applicationsViewer.setContentProvider(new TreeContentProvider());
    applicationsViewer.setLabelProvider(new ServerLabelProvider() {
        @Override
        public Image getImage(Object element) {
            Image image = super.getImage(element);

            if (element instanceof IModule) {
                IModule module = (IModule) element;
                DockerFoundryApplicationModule appModule = editorPage.getCloudServer()
                        .getExistingCloudModule(module);
                if (appModule != null && appModule.getErrorMessage() != null) {
                    return DockerFoundryImages.getImage(new DecorationOverlayIcon(image,
                            DockerFoundryImages.OVERLAY_ERROR, IDecoration.BOTTOM_LEFT));
                }
            }

            return image;
        }

        @Override
        public String getText(Object element) {
            // This is the WTP module name (usually, it's the workspace
            // project name)
            String moduleName = super.getText(element);

            // However, the user has the option to specify a different name
            // when pushing an app, which is used as the cf app name. If
            // they are different, and the
            // corresponding workspace project is accessible, show both.
            // Otherwise, show the cf app name.

            if (element instanceof IModule) {

                IModule module = (IModule) element;

                // Find the corresponding Cloud Foundry-aware application
                // Module.
                DockerFoundryApplicationModule appModule = cloudServer
                        .getExistingCloudModule((IModule) element);

                if (appModule != null) {
                    String cfAppName = appModule.getDeployedApplicationName();

                    if (cfAppName != null) {

                        // Be sure not to show a null WTP module name,
                        // although
                        // that should not be encountered
                        if (moduleName != null && !cfAppName.equals(moduleName)
                                && DockerFoundryProperties.isModuleProjectAccessible
                                        .testProperty(new IModule[] { module }, cloudServer)) {
                            moduleName = cfAppName + " (" + moduleName + ")"; //$NON-NLS-1$ //$NON-NLS-2$
                        } else {
                            moduleName = cfAppName;
                        }
                    }
                }
            }

            return moduleName;
        }

    });
    applicationsViewer.setInput(new CloudApplication[0]);
    applicationsViewer.setSorter(new DockerFoundryViewerSorter());

    applicationsViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            IModule module = (IModule) selection.getFirstElement();

            if (currentModule != module) {
                currentModule = module;
                getManagedForm().fireSelectionChanged(ApplicationMasterPart.this, selection);
            }
        }
    });
    GridDataFactory.fillDefaults().grab(true, true).hint(250, SWT.DEFAULT)
            .applyTo(applicationsViewer.getControl());

    int ops = DND.DROP_COPY | DND.DROP_LINK | DND.DROP_DEFAULT;
    Transfer[] transfers = new Transfer[] { LocalSelectionTransfer.getTransfer() };
    ApplicationViewersDropAdapter listener = new ApplicationViewersDropAdapter(applicationsViewer);
    applicationsViewer.addDropSupport(ops, transfers, listener);

    // create context menu
    MenuManager menuManager = new MenuManager();
    menuManager.setRemoveAllWhenShown(true);
    menuManager.addMenuListener(new IMenuListener() {

        public void menuAboutToShow(IMenuManager manager) {
            fillApplicationsContextMenu(manager);
        }
    });

    Menu menu = menuManager.createContextMenu(applicationsViewer.getControl());
    applicationsViewer.getControl().setMenu(menu);
    editorPage.getSite().registerContextMenu(menuManager, applicationsViewer);

    Action addRemoveApplicationAction = new Action(Messages.ApplicationMasterPart_TEXT_ADD_REMOVE,
            ImageResource.getImageDescriptor(ImageResource.IMG_ETOOL_MODIFY_MODULES)) {
        @Override
        public void run() {
            ModifyModulesWizard wizard = new ModifyModulesWizard(cloudServer.getServerOriginal());
            WizardDialog dialog = new WizardDialog(getSection().getShell(), wizard);
            dialog.open();
        }
    };
    toolBarManager.add(addRemoveApplicationAction);

    // Fix for STS-2996. Moved from CloudFoundryApplicationsEditorPage
    toolBarManager.add(RefreshEditorAction.getRefreshAction(editorPage, null));
    toolBarManager.update(true);
    section.setTextClient(headerComposite);

    getManagedForm().getToolkit().paintBordersFor(client);
}

From source file:cn.dockerfoundry.ide.eclipse.server.ui.internal.editor.ApplicationMasterPart.java

License:Open Source License

private void createServicesSection() {
    servicesSection = toolkit.createSection(getSection().getParent(),
            Section.TITLE_BAR | Section.DESCRIPTION | Section.TWISTIE);
    servicesSection.setLayout(new GridLayout());
    GridDataFactory.fillDefaults().grab(true, true).applyTo(servicesSection);
    servicesSection.setText(Messages.COMMONTXT_SERVICES);
    servicesSection.setExpanded(true);/*from   ww w.  j av a2 s.c om*/
    servicesSection.setDescription(Messages.ApplicationMasterPart_TEXT_SERVICES_DESCRIP);
    // NOTE:Comment out as keeping section collapsed by default causes zero
    // height tables if no services are provided
    // servicesSection.addExpansionListener(new ExpansionAdapter() {
    //
    // @Override
    // public void expansionStateChanged(ExpansionEvent e) {
    // userExpanded = true;
    // }
    // });

    Composite client = toolkit.createComposite(servicesSection);
    client.setLayout(new GridLayout());
    GridDataFactory.fillDefaults().grab(true, true).applyTo(client);
    servicesSection.setClient(client);

    Composite headerComposite = toolkit.createComposite(servicesSection, SWT.NONE);
    RowLayout rowLayout = new RowLayout();
    rowLayout.marginTop = 0;
    rowLayout.marginBottom = 0;
    headerComposite.setLayout(rowLayout);
    headerComposite.setBackground(null);

    ToolBarManager toolBarManager = new ToolBarManager(SWT.FLAT);
    toolBarManager.createControl(headerComposite);

    servicesViewer = new TableViewer(toolkit.createTable(client, SWT.MULTI));
    new ServiceViewerConfigurator().configureViewer(servicesViewer);

    servicesViewer.setContentProvider(new TreeContentProvider());
    servicesViewer.setLabelProvider(new ServicesTreeLabelProvider(servicesViewer) {

        protected Image getColumnImage(CloudService service, ServiceViewColumn column) {
            return null;
        }

    });
    servicesViewer.setSorter(new ServiceViewerSorter(servicesViewer) {

        @Override
        protected int compare(DockerApplicationService service1, DockerApplicationService service2,
                ServiceViewColumn sortColumn) {

            return super.compare(service1, service2, sortColumn);
        }

    });
    DockerApplicationService[] servicesArray = new DockerApplicationService[this.services.size()];
    this.services.toArray(servicesArray);
    servicesViewer.setInput(servicesArray);
    //      servicesViewer.setInput(this.services);

    GridDataFactory.fillDefaults().grab(true, true).applyTo(servicesViewer.getControl());

    //      Action addServiceAction = new Action(Messages.COMMONTXT_ADD_SERVICE, CloudFoundryImages.NEW_SERVICE) {
    //         @Override
    //         public void run() {
    //            CloudFoundryServiceWizard wizard = new CloudFoundryServiceWizard(cloudServer);
    //            WizardDialog dialog = new WizardDialog(getSection().getShell(), wizard);
    //            wizard.setParent(dialog);
    //            dialog.setPageSize(900, 600);
    //            dialog.setBlockOnOpen(true);
    //            dialog.open();
    //         }
    //      };
    //      toolBarManager.add(addServiceAction);
    //      toolBarManager.update(true);
    servicesSection.setTextClient(headerComposite);

    // create context menu
    //      MenuManager menuManager = new MenuManager();
    //      menuManager.setRemoveAllWhenShown(true);
    //      menuManager.addMenuListener(new IMenuListener() {
    //
    //         public void menuAboutToShow(IMenuManager manager) {
    //            fillServicesContextMenu(manager);
    //         }
    //      });

    //      Menu menu = menuManager.createContextMenu(servicesViewer.getControl());
    //      servicesViewer.getControl().setMenu(menu);
    //      editorPage.getSite().registerContextMenu(menuManager, servicesViewer);

    // Create drag source on the table
    int ops = DND.DROP_COPY;
    Transfer[] transfers = new Transfer[] { LocalSelectionTransfer.getTransfer() };
    DragSourceAdapter listener = new DragSourceAdapter() {
        @Override
        public void dragSetData(DragSourceEvent event) {
            IStructuredSelection selection = (IStructuredSelection) servicesViewer.getSelection();
            event.data = selection.getFirstElement();
            LocalSelectionTransfer.getTransfer().setSelection(selection);
        }

        @Override
        public void dragStart(DragSourceEvent event) {
            if (event.detail == DND.DROP_NONE || event.detail == DND.DROP_DEFAULT) {
                event.detail = DND.DROP_COPY;
            }
            dragSetData(event);
        }

    };
    servicesViewer.addDragSupport(ops, transfers, listener);

    getManagedForm().getToolkit().paintBordersFor(client);

}

From source file:cn.dockerfoundry.ide.eclipse.server.ui.internal.editor.ApplicationMasterPart.java

License:Open Source License

private void fillApplicationsContextMenu(IMenuManager manager) {
    IStructuredSelection selection = (IStructuredSelection) applicationsViewer.getSelection();
    if (selection.isEmpty()) {
        return;//  w  ww . j a  v a  2s . com
    }

    IModule module = (IModule) selection.getFirstElement();
    if (module != null) {
        manager.add(
                new RemoveModuleAction(getSection().getShell(), editorPage.getServer().getOriginal(), module));

    }
}

From source file:cn.ieclipse.adt.ext.helpers.ProjectHelper.java

License:Apache License

/**
 * Utility method to inspect a selection to find a Java element.
 * /*  w  w w . ja  v  a 2  s.  c  o m*/
 * @param selection
 *            the selection to be inspected
 * @return a Java element to be used as the initial selection, or
 *         <code>null</code>, if no Java element exists in the given
 *         selection
 */
public static IJavaElement getInitialJavaElement(IStructuredSelection selection) {
    IJavaElement jelem = null;
    if (selection != null && !selection.isEmpty()) {
        Object selectedElement = selection.getFirstElement();
        System.out.println(selectedElement.getClass());
        if (selectedElement instanceof IAdaptable) {
            IAdaptable adaptable = (IAdaptable) selectedElement;

            jelem = (IJavaElement) adaptable.getAdapter(IJavaElement.class);
            if (jelem == null || !jelem.exists()) {
                jelem = null;
                IResource resource = (IResource) adaptable.getAdapter(IResource.class);
                if (resource != null && resource.getType() != IResource.ROOT) {
                    while (jelem == null && resource.getType() != IResource.PROJECT) {
                        resource = resource.getParent();
                        jelem = (IJavaElement) resource.getAdapter(IJavaElement.class);
                    }
                    if (jelem == null) {
                        jelem = JavaCore.create(resource); // java project
                    }
                }
            }
        }
    }
    return jelem;
}

From source file:cn.ieclipse.adt.ext.wizards.EditComponentWizardPage.java

License:Apache License

public void createControl(Composite parent) {

    GC gc = new GC(parent);
    gc.setFont(parent.getFont());/*from   www .j a v  a  2 s .c  om*/
    fontMetrics = gc.getFontMetrics();
    gc.dispose();
    // for (ComponentAttribute attr : attributes) {
    // createAttrFiled(container, layout.numColumns, attr);
    // }
    SashForm sashForm = new SashForm(parent, SWT.NONE);
    sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    Composite composite_1 = new Composite(sashForm, SWT.NONE);
    composite_1.setLayout(new GridLayout(1, false));

    ToolBar toolBar = new ToolBar(composite_1, SWT.FLAT | SWT.RIGHT);
    toolBar.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1));

    final ToolItem tbAdd = new ToolItem(toolBar, SWT.NONE);
    tbAdd.setToolTipText("Add");
    tbAdd.setImage(ADD_IMG);

    final ToolItem tbDelete = new ToolItem(toolBar, SWT.NONE);
    tbDelete.setImage(DEL_IMG);
    tbDelete.setToolTipText("Delete");

    final ToolItem tbUp = new ToolItem(toolBar, SWT.NONE);
    tbUp.setToolTipText("Up");
    tbUp.setImage(UP_IMG);

    final ToolItem tbDown = new ToolItem(toolBar, SWT.NONE);
    tbDown.setToolTipText("Down");
    tbDown.setImage(DOWN_IMG);

    tbAdd.addSelectionListener(new MenuItemSelectionAdapter(MID_ADD));
    tbDelete.addSelectionListener(new MenuItemSelectionAdapter(MID_DELETE));
    tbUp.addSelectionListener(new MenuItemSelectionAdapter(MID_UP));
    tbDown.addSelectionListener(new MenuItemSelectionAdapter(MID_DOWN));
    tbAdd.setEnabled(false);
    tbDelete.setEnabled(false);
    tbUp.setEnabled(false);
    tbDown.setEnabled(false);

    final ToolItem tbTip = new ToolItem(toolBar, SWT.CHECK);
    tbTip.setImage(SWTResourceManager.getImage(org.eclipse.jdt.ui.ISharedImages.class,
            "/icons/full/obj16/translate.png"));
    tbTip.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            TipShell.setShow(tbTip.getSelection());
            if (tbTip.getSelection()) {
                tbTip.setImage(SWTResourceManager.getImage(org.eclipse.jdt.ui.ISharedImages.class,
                        "/icons/full/obj16/never_translate.png"));
            } else {
                tbTip.setImage(SWTResourceManager.getImage(org.eclipse.jdt.ui.ISharedImages.class,
                        "/icons/full/obj16/translate.png"));
            }
        }
    });

    tbTip.setToolTipText("Show/Hide tooltip text for attribute");
    // tbTip.setText("Show attribute tooltip");

    treeViewer = new TreeViewer(composite_1, SWT.BORDER);
    Tree tree = treeViewer.getTree();
    tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    Menu menu = new Menu(tree);
    tree.setMenu(menu);

    final MenuItem miAdd = new MenuItem(menu, SWT.NONE);
    miAdd.setText("Add");
    miAdd.setID(MID_ADD);
    miAdd.setImage(ADD_IMG);

    // final MenuItem miCopy = new MenuItem(menu, SWT.NONE);
    // miCopy.setText("Copy");
    // miCopy.setID(MID_COPY);
    //
    // final MenuItem miPaste = new MenuItem(menu, SWT.NONE);
    // miPaste.setText("Paste");
    // miPaste.setID(MID_PASTE);

    final MenuItem miDel = new MenuItem(menu, SWT.NONE);
    miDel.setText("Delete");
    miDel.setID(MID_DELETE);
    miDel.setImage(DEL_IMG);

    final MenuItem miUp = new MenuItem(menu, SWT.NONE);
    miUp.setText("Up");
    miUp.setID(MID_UP);
    miUp.setImage(UP_IMG);

    final MenuItem miDown = new MenuItem(menu, SWT.NONE);
    miDown.setText("Down");
    miDown.setID(MID_DOWN);
    miDown.setImage(DOWN_IMG);

    miAdd.addSelectionListener(new MenuItemSelectionAdapter(MID_ADD));
    miDel.addSelectionListener(new MenuItemSelectionAdapter(MID_DELETE));
    miUp.addSelectionListener(new MenuItemSelectionAdapter(MID_UP));
    miDown.addSelectionListener(new MenuItemSelectionAdapter(MID_DOWN));

    menu.addMenuListener(new MenuAdapter() {
        @Override
        public void menuShown(MenuEvent e) {
            miUp.setEnabled(selectedNode != rootNode);
            miDown.setEnabled(selectedNode != rootNode);

            boolean canAdd = selectedNode != null;
            if (canAdd) {
                ComponentElement ce = getNodeAttrCache().get(selectedNode);
                canAdd = canAdd && !ce.getChildren().isEmpty();
                miAdd.setEnabled(canAdd);
            }
        }
    });

    treeViewer.setLabelProvider(new NodeLabelProvider());
    treeViewer.setContentProvider(new NodeContentProvider());
    treeViewer.setAutoExpandLevel(5);

    treeViewer.setInput(rootNode);
    treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection sel = (IStructuredSelection) event.getSelection();
            update(sel.getFirstElement());

            tbUp.setEnabled(selectedNode != rootNode);
            tbDown.setEnabled(selectedNode != rootNode);
            tbDelete.setEnabled(selectedNode != null);

            boolean canAdd = selectedNode != null;
            if (canAdd) {
                ComponentElement ce = getNodeAttrCache().get(selectedNode);
                canAdd = canAdd && !ce.getChildren().isEmpty();
                tbAdd.setEnabled(canAdd);
            }
            fireTreeUpdated();
        }
    });
    treeViewer.getTree().forceFocus();
    treeViewer.setAutoExpandLevel(3);

    scrolledComposite = new ScrolledComposite(sashForm, SWT.H_SCROLL | SWT.V_SCROLL);
    scrolledComposite.setExpandHorizontal(true);
    scrolledComposite.setExpandVertical(true);

    scrolledComposite.setLayout(new FillLayout());
    composite = new Composite(scrolledComposite, SWT.NONE);
    scrolledComposite.setContent(composite);
    layout = new GridLayout();
    layout.numColumns = 4;
    layout.makeColumnsEqualWidth = false;
    composite.setLayout(layout);
    scrolledComposite.setMinSize(480, 320);
    sashForm.setWeights(new int[] { 400, 480 });
    setControl(sashForm);
}

From source file:cn.ieclipse.adt.ext.wizards.ElementTableSelector.java

License:Apache License

public ElementTableSelector(final Composite composite, GridData gridData, final String groupDescr,
        final String selectionMessage, final Object[] elements) {
    this.elements = elements;
    Group intentGroup = new Group(composite, SWT.NONE);
    intentGroup.setLayout(new GridLayout(2, false));
    intentGroup.setLayoutData(gridData);
    intentGroup.setText(groupDescr);//from   ww w.j  av a  2 s.c  om

    tv = new TableViewer(intentGroup, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.FULL_SELECTION);
    table = tv.getTable();
    table.setHeaderVisible(false);
    table.setLinesVisible(true);

    table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    final Menu menu = new Menu(tv.getControl());
    MenuItem add = new MenuItem(menu, SWT.PUSH);
    add.setText("&Add Custom");
    add.setImage(ADD_IMG);
    add.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            addModel(new Model("custom"));
            tv.refresh();
        }
    });

    MenuItem up = new MenuItem(menu, SWT.PUSH);
    up.setText("&Up");
    up.setImage(UP_IMG);
    up.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            IStructuredSelection sel = (IStructuredSelection) tv.getSelection();
            if (!sel.isEmpty()) {
                Model m = (Model) sel.getFirstElement();
                int idx = selectedElements.indexOf(m);
                if (idx > 0) {
                    Model n = selectedElements.get(idx - 1);
                    selectedElements.set(idx, n);
                    selectedElements.set(idx - 1, m);

                    tv.refresh();
                }

            }
        }
    });

    MenuItem down = new MenuItem(menu, SWT.PUSH);
    down.setText("&Down");
    down.setImage(DOWN_IMG);
    down.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            IStructuredSelection sel = (IStructuredSelection) tv.getSelection();
            if (!sel.isEmpty()) {
                Model m = (Model) sel.getFirstElement();
                int idx = selectedElements.indexOf(m);
                if (idx < selectedElements.size() - 1) {
                    Model n = selectedElements.get(idx + 1);
                    selectedElements.set(idx, n);
                    selectedElements.set(idx + 1, m);

                    tv.refresh();
                }

            }
        }
    });

    table.setMenu(menu);

    tv.setContentProvider(new MyContentProvider());

    ColumnViewerToolTipSupport.enableFor(tv, ToolTip.NO_RECREATE);
    // TableViewerFocusCellManager focusCellManager = new
    // TableViewerFocusCellManager(
    // tv, new FocusBorderCellHighlighter(tv));
    ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(tv) {
        protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) {
            return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
                    || event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
                    || (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED
                            && event.keyCode == SWT.CR)
                    || event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
        }
    };

    TableViewerEditor.create(tv, null, actSupport,
            ColumnViewerEditor.TABBING_HORIZONTAL | ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
                    | ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION);

    final TableViewerColumn col = new TableViewerColumn(tv, SWT.NONE);
    col.setLabelProvider(new MyCellLabelProvider());
    col.setEditingSupport(new MyEditingSupport(tv));
    // tv.getTable().
    col.getColumn().setWidth(300);

    table.addControlListener(new ControlListener() {

        public void controlResized(ControlEvent e) {
            int w = table.getClientArea().width;
            if (w > 0) {
                col.getColumn().setWidth(w);
            }
        }

        public void controlMoved(ControlEvent e) {

        }
    });

    tv.setInput(selectedElements);

    Composite buttonComp = new Composite(intentGroup, SWT.NONE);
    buttonComp.setLayout(new FillLayout(SWT.VERTICAL));
    addButton = new Button(buttonComp, SWT.NONE);
    addButton.setText("Add...");
    addButton.addSelectionListener(new SelectionListener() {
        public void widgetSelected(SelectionEvent e) {
            showSelectionDialog(composite, selectionMessage);
        }

        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });

    removeButton = new Button(buttonComp, SWT.NONE);
    removeButton.setText("Remove...");
    removeButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            int[] selection = table.getSelectionIndices();
            if (selection != null) {
                IStructuredSelection sel = (IStructuredSelection) tv.getSelection();
                if (!sel.isEmpty()) {
                    for (Object object : sel.toArray()) {
                        selectedElements.remove(object);
                    }
                }
                tv.refresh();
            }
        }
    });
}

From source file:cn.ieclipse.aorm.eclipse.helpers.ProjectHelper.java

License:Apache License

/**
 * Utility method to inspect a selection to find a Java element.
 * //from w w  w.j  ava  2 s.com
 * @param selection
 *            the selection to be inspected
 * @return a Java element to be used as the initial selection, or
 *         <code>null</code>, if no Java element exists in the given
 *         selection
 */
public static IJavaElement getInitialJavaElement(IStructuredSelection selection) {
    IJavaElement jelem = null;
    if (selection != null && !selection.isEmpty()) {
        Object selectedElement = selection.getFirstElement();
        if (selectedElement instanceof IAdaptable) {
            IAdaptable adaptable = (IAdaptable) selectedElement;

            jelem = (IJavaElement) adaptable.getAdapter(IJavaElement.class);
            if (jelem == null || !jelem.exists()) {
                jelem = null;
                IResource resource = (IResource) adaptable.getAdapter(IResource.class);
                if (resource != null && resource.getType() != IResource.ROOT) {
                    while (jelem == null && resource.getType() != IResource.PROJECT) {
                        resource = resource.getParent();
                        jelem = (IJavaElement) resource.getAdapter(IJavaElement.class);
                    }
                    if (jelem == null) {
                        jelem = JavaCore.create(resource); // java project
                    }
                }
            }
        }
    }
    return jelem;
}