Example usage for org.eclipse.swt.widgets Composite setLayout

List of usage examples for org.eclipse.swt.widgets Composite setLayout

Introduction

In this page you can find the example usage for org.eclipse.swt.widgets Composite setLayout.

Prototype

public void setLayout(Layout layout) 

Source Link

Document

Sets the layout which is associated with the receiver to be the argument which may be null.

Usage

From source file:fr.inria.soctrace.framesoc.ui.histogram.view.HistogramView.java

@Override
public void createFramesocPartControl(Composite parent) {

    statusLineManager = getViewSite().getActionBars().getStatusLineManager();

    // parent layout
    GridLayout gl_parent = new GridLayout(1, false);
    gl_parent.verticalSpacing = 2;/* www .  j  a va2 s  .co  m*/
    gl_parent.marginWidth = 0;
    gl_parent.horizontalSpacing = 0;
    gl_parent.marginHeight = 0;
    parent.setLayout(gl_parent);

    // Sash
    SashForm sashForm = new SashForm(parent, SWT.NONE);
    sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    // Chart Composite
    compositeChart = new Composite(sashForm, SWT.BORDER);
    FillLayout fl_compositeChart = new FillLayout(SWT.HORIZONTAL);
    compositeChart.setLayout(fl_compositeChart);
    compositeChart.addControlListener(new ControlAdapter() {
        @Override
        public void controlResized(ControlEvent e) {
            int width = Math.max(compositeChart.getSize().x - 40, 1);
            numberOfTicks = Math.max(width / TIMESTAMP_MAX_SIZE, 1);
            refresh(false, false, true);
        }
    });

    // Configuration Composite
    compositeConf = new Composite(sashForm, SWT.NONE);
    GridLayout gl_compositeConf = new GridLayout(1, false);
    gl_compositeConf.marginHeight = 1;
    gl_compositeConf.verticalSpacing = 0;
    gl_compositeConf.marginWidth = 0;
    compositeConf.setLayout(gl_compositeConf);
    compositeConf.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    // Tab folder
    TabFolder tabFolder = new TabFolder(compositeConf, SWT.NONE);
    tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    PatternFilter filter = new TreePatternFilter();
    TreeContentProvider contentProvider = new TreeContentProvider();
    ViewerComparator treeComparator = new ViewerComparator();
    SelectionChangedListener selectionChangeListener = new SelectionChangedListener();
    CheckStateListener checkStateListener = new CheckStateListener();

    SquareIconLabelProvider p = null;

    // Tab item types
    TabItem tbtmEventTypes = new TabItem(tabFolder, SWT.NONE);
    tbtmEventTypes.setData(ConfigurationDimension.TYPE);
    tbtmEventTypes.setText(ConfigurationDimension.TYPE.getName());
    filter.setIncludeLeadingWildcard(true);
    FilteredCheckboxTree typeTree = new FilteredCheckboxTree(tabFolder, SWT.BORDER, filter, true);
    configurationMap.get(ConfigurationDimension.TYPE).tree = typeTree;
    typeTree.getViewer().setContentProvider(contentProvider);
    p = new EventTypeTreeLabelProvider();
    labelProviders.add(p);
    typeTree.getViewer().setLabelProvider(p);
    typeTree.getViewer().setComparator(treeComparator);
    typeTree.addCheckStateListener(checkStateListener);
    typeTree.getViewer().addSelectionChangedListener(selectionChangeListener);
    tbtmEventTypes.setControl(typeTree);

    // Tab item producers
    TabItem tbtmEventProducers = new TabItem(tabFolder, SWT.NONE);
    tbtmEventProducers.setData(ConfigurationDimension.PRODUCERS);
    tbtmEventProducers.setText(ConfigurationDimension.PRODUCERS.getName());
    FilteredCheckboxTree prodTree = new FilteredCheckboxTree(tabFolder, SWT.BORDER, filter, true);
    configurationMap.get(ConfigurationDimension.PRODUCERS).tree = prodTree;
    prodTree.getViewer().setContentProvider(contentProvider);
    p = new EventProducerTreeLabelProvider();
    labelProviders.add(p);
    prodTree.getViewer().setLabelProvider(p);
    prodTree.getViewer().setComparator(treeComparator);
    prodTree.addCheckStateListener(checkStateListener);
    prodTree.getViewer().addSelectionChangedListener(selectionChangeListener);
    tbtmEventProducers.setControl(prodTree);

    // sash weights
    sashForm.setWeights(new int[] { 80, 20 });
    // tab switch
    tabFolder.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            currentDimension = (ConfigurationDimension) event.item.getData();
            enableTreeButtons();
            enableSubTreeButtons();
        }
    });

    // Buttons
    Composite compositeBtn = new Composite(compositeConf, SWT.BORDER);
    GridLayout gl_compositeBtn = new GridLayout(10, false);
    gl_compositeBtn.marginWidth = 1;
    gl_compositeBtn.horizontalSpacing = 1;
    compositeBtn.setLayout(gl_compositeBtn);
    compositeBtn.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false, 1, 1));

    btnCheckall = new Button(compositeBtn, SWT.NONE);
    btnCheckall.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1));
    btnCheckall.setToolTipText("Check all");
    btnCheckall.setImage(ResourceManager.getPluginImage(Activator.PLUGIN_ID, "icons/check_all.png"));
    btnCheckall.setEnabled(false);
    btnCheckall.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (configurationMap.get(currentDimension).roots != null) {
                FilteredCheckboxTree tree = configurationMap.get(currentDimension).tree;
                TreeContentProvider provider = (TreeContentProvider) tree.getViewer().getContentProvider();
                Object[] roots = provider.getElements(tree.getViewer().getInput());
                for (Object root : roots) {
                    checkElementAndSubtree(root);
                }
                selectionChanged();
            }
        }
    });

    btnUncheckall = new Button(compositeBtn, SWT.NONE);
    btnUncheckall.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
    btnUncheckall.setToolTipText("Uncheck all");
    btnUncheckall.setImage(ResourceManager.getPluginImage(Activator.PLUGIN_ID, "icons/uncheck_all.png"));
    btnUncheckall.setEnabled(false);
    btnUncheckall.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            configurationMap.get(currentDimension).tree.setCheckedElements(EMPTY_ARRAY);
            selectionChanged();
        }
    });

    Label separator = new Label(compositeBtn, SWT.SEPARATOR | SWT.VERTICAL);
    GridData gd_separator = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
    gd_separator.horizontalIndent = 2;
    gd_separator.widthHint = 5;
    gd_separator.heightHint = 20;
    separator.setLayoutData(gd_separator);

    btnCheckSubtree = new Button(compositeBtn, SWT.NONE);
    btnCheckSubtree.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
    btnCheckSubtree.setToolTipText("Check subtree");
    btnCheckSubtree.setImage(ResourceManager.getPluginImage(Activator.PLUGIN_ID, "icons/check_subtree.png"));
    btnCheckSubtree.setEnabled(false);
    btnCheckSubtree.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (configurationMap.get(currentDimension).roots != null) {
                ITreeNode node = getCurrentSelection(configurationMap.get(currentDimension).tree);
                if (node == null)
                    return;
                checkElementAndSubtree(node);
                selectionChanged();
            }
        }
    });

    btnUncheckSubtree = new Button(compositeBtn, SWT.NONE);
    btnUncheckSubtree.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
    btnUncheckSubtree.setToolTipText("Uncheck subtree");
    btnUncheckSubtree
            .setImage(ResourceManager.getPluginImage(Activator.PLUGIN_ID, "icons/uncheck_subtree.png"));
    btnUncheckSubtree.setEnabled(false);
    btnUncheckSubtree.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (configurationMap.get(currentDimension).roots != null) {
                ITreeNode node = getCurrentSelection(configurationMap.get(currentDimension).tree);
                if (node == null)
                    return;
                uncheckElement(node);
                uncheckAncestors(node);
                selectionChanged();
            }
        }
    });

    // Time management bar
    Composite timeComposite = new Composite(parent, SWT.BORDER);
    timeComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
    GridLayout gl_timeComposite = new GridLayout(1, false);
    gl_timeComposite.horizontalSpacing = 0;
    timeComposite.setLayout(gl_timeComposite);
    // time manager
    timeBar = new TimeBar(timeComposite, SWT.NONE, true, true);
    timeBar.setEnabled(false);
    IStatusLineManager statusLineManager = getViewSite().getActionBars().getStatusLineManager();
    timeBar.setStatusLineManager(statusLineManager);
    timeBar.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            TimeInterval barInterval = timeBar.getSelection();
            if (marker == null) {
                addNewMarker(barInterval.startTimestamp, barInterval.endTimestamp);
            } else {
                marker.setStartValue(barInterval.startTimestamp);
                marker.setEndValue(barInterval.endTimestamp);
            }
            selectedTs0 = barInterval.startTimestamp;
            selectedTs1 = barInterval.endTimestamp;
            timeChanged = !barInterval.equals(loadedInterval);
        }
    });
    // button to synch the timebar, producers and type with the current loaded data
    timeBar.getSynchButton().setToolTipText("Reset Timebar, Types and Producers");
    timeBar.getSynchButton().addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (loadedInterval != null) {
                timeBar.setSelection(loadedInterval);
                if (marker != null && plot != null) {
                    plot.removeDomainMarker(marker);
                    marker = null;
                }
            }
            for (ConfigurationData data : configurationMap.values()) {
                data.tree.setCheckedElements(data.checked);
            }
            timeChanged = false;
            enableTreeButtons();
            enableSubTreeButtons();
        }
    });
    // load button
    timeBar.getLoadButton().addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (timeChanged || configurationChanged) {
                loadHistogram(currentShownTrace, timeBar.getSelection());
            }
        }
    });

    // build toolbar
    IActionBars actionBars = getViewSite().getActionBars();
    IToolBarManager toolBar = actionBars.getToolBarManager();
    TableTraceIntervalAction.add(toolBar, createTableAction());
    GanttTraceIntervalAction.add(toolBar, createGanttAction());
    PieTraceIntervalAction.add(toolBar, createPieAction());
    enableActions(false);
}

From source file:org.eclipse.swt.examples.fileviewer.FileViewer.java

/**
 * Creates the file details table./*  w  w  w .  j  ava  2 s . com*/
 *
 * @param parent the parent control
 */
private void createTableView(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 1;
    gridLayout.marginHeight = gridLayout.marginWidth = 2;
    gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
    composite.setLayout(gridLayout);
    tableContentsOfLabel = new Label(composite, SWT.BORDER);
    tableContentsOfLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));

    table = new Table(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
    table.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));

    for (int i = 0; i < tableTitles.length; ++i) {
        TableColumn column = new TableColumn(table, SWT.NONE);
        column.setText(tableTitles[i]);
        column.setWidth(tableWidths[i]);
    }
    table.setHeaderVisible(true);
    table.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            notifySelectedFiles(getSelectedFiles());
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent event) {
            doDefaultFileAction(getSelectedFiles());
        }

        private File[] getSelectedFiles() {
            final TableItem[] items = table.getSelection();
            final File[] files = new File[items.length];

            for (int i = 0; i < items.length; ++i) {
                files[i] = (File) items[i].getData(TABLEITEMDATA_FILE);
            }
            return files;
        }
    });

    createTableDragSource(table);
    createTableDropTarget(table);
}

From source file:org.eclipse.swt.examples.fileviewer.FileViewer.java

/**
 * Creates the file tree view./*from   w  w w.  j  a  v  a 2 s  .c  om*/
 *
 * @param parent the parent control
 */
private void createTreeView(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 1;
    gridLayout.marginHeight = gridLayout.marginWidth = 2;
    gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
    composite.setLayout(gridLayout);

    treeScopeLabel = new Label(composite, SWT.BORDER);
    treeScopeLabel.setText(FileViewer.getResourceString("details.AllFolders.text"));
    treeScopeLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));

    tree = new Tree(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE);
    tree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));

    tree.addSelectionListener(new SelectionListener() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            final TreeItem[] selection = tree.getSelection();
            if (selection != null && selection.length != 0) {
                TreeItem item = selection[0];
                File file = (File) item.getData(TREEITEMDATA_FILE);

                notifySelectedDirectory(file);
            }
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent event) {
            final TreeItem[] selection = tree.getSelection();
            if (selection != null && selection.length != 0) {
                TreeItem item = selection[0];
                item.setExpanded(true);
                treeExpandItem(item);
            }
        }
    });
    tree.addTreeListener(new TreeAdapter() {
        @Override
        public void treeExpanded(TreeEvent event) {
            final TreeItem item = (TreeItem) event.item;
            final Image image = (Image) item.getData(TREEITEMDATA_IMAGEEXPANDED);
            if (image != null)
                item.setImage(image);
            treeExpandItem(item);
        }

        @Override
        public void treeCollapsed(TreeEvent event) {
            final TreeItem item = (TreeItem) event.item;
            final Image image = (Image) item.getData(TREEITEMDATA_IMAGECOLLAPSED);
            if (image != null)
                item.setImage(image);
        }
    });
    createTreeDragSource(tree);
    createTreeDropTarget(tree);
}

From source file:org.eclipse.swt.examples.texteditor.TextEditor.java

void createToolBar() {
    coolBar = new CoolBar(shell, SWT.FLAT);
    ToolBar styleToolBar = new ToolBar(coolBar, SWT.FLAT);
    boldControl = new ToolItem(styleToolBar, SWT.CHECK);
    boldControl.setImage(iBold);//from  ww  w .  ja  v a 2s .c o  m
    boldControl.setToolTipText(getResourceString("Bold")); //$NON-NLS-1$
    boldControl.addSelectionListener(widgetSelectedAdapter(event -> setStyle(BOLD)));

    italicControl = new ToolItem(styleToolBar, SWT.CHECK);
    italicControl.setImage(iItalic);
    italicControl.setToolTipText(getResourceString("Italic")); //$NON-NLS-1$
    italicControl.addSelectionListener(widgetSelectedAdapter(event -> setStyle(ITALIC)));

    final Menu underlineMenu = new Menu(shell, SWT.POP_UP);
    underlineSingleItem = new MenuItem(underlineMenu, SWT.RADIO);
    underlineSingleItem.setText(getResourceString("Single_menuitem")); //$NON-NLS-1$
    underlineSingleItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (underlineSingleItem.getSelection()) {
            setStyle(UNDERLINE_SINGLE);
        }
    }));
    underlineSingleItem.setSelection(true);

    underlineDoubleItem = new MenuItem(underlineMenu, SWT.RADIO);
    underlineDoubleItem.setText(getResourceString("Double_menuitem")); //$NON-NLS-1$
    underlineDoubleItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (underlineDoubleItem.getSelection()) {
            setStyle(UNDERLINE_DOUBLE);
        }
    }));

    underlineSquiggleItem = new MenuItem(underlineMenu, SWT.RADIO);
    underlineSquiggleItem.setText(getResourceString("Squiggle_menuitem")); //$NON-NLS-1$
    underlineSquiggleItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (underlineSquiggleItem.getSelection()) {
            setStyle(UNDERLINE_SQUIGGLE);
        }
    }));

    underlineErrorItem = new MenuItem(underlineMenu, SWT.RADIO);
    underlineErrorItem.setText(getResourceString("Error_menuitem")); //$NON-NLS-1$
    underlineErrorItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (underlineErrorItem.getSelection()) {
            setStyle(UNDERLINE_ERROR);
        }
    }));

    MenuItem underlineColorItem = new MenuItem(underlineMenu, SWT.PUSH);
    underlineColorItem.setText(getResourceString("Color_menuitem")); //$NON-NLS-1$
    underlineColorItem.addSelectionListener(widgetSelectedAdapter(event -> {
        ColorDialog dialog = new ColorDialog(shell);
        RGB rgb = underlineColor != null ? underlineColor.getRGB() : null;
        dialog.setRGB(rgb);
        RGB newRgb = dialog.open();
        if (newRgb != null) {
            if (!newRgb.equals(rgb)) {
                disposeResource(underlineColor);
                underlineColor = new Color(display, newRgb);
            }
            if (underlineSingleItem.getSelection())
                setStyle(UNDERLINE_SINGLE);
            else if (underlineDoubleItem.getSelection())
                setStyle(UNDERLINE_DOUBLE);
            else if (underlineErrorItem.getSelection())
                setStyle(UNDERLINE_ERROR);
            else if (underlineSquiggleItem.getSelection())
                setStyle(UNDERLINE_SQUIGGLE);
        }
    }));

    final ToolItem underlineControl = new ToolItem(styleToolBar, SWT.DROP_DOWN);
    underlineControl.setImage(iUnderline);
    underlineControl.setToolTipText(getResourceString("Underline")); //$NON-NLS-1$
    underlineControl.addSelectionListener(widgetSelectedAdapter(event -> {
        if (event.detail == SWT.ARROW) {
            Rectangle rect = underlineControl.getBounds();
            Point pt = new Point(rect.x, rect.y + rect.height);
            underlineMenu.setLocation(display.map(underlineControl.getParent(), null, pt));
            underlineMenu.setVisible(true);
        } else {
            if (underlineSingleItem.getSelection())
                setStyle(UNDERLINE_SINGLE);
            else if (underlineDoubleItem.getSelection())
                setStyle(UNDERLINE_DOUBLE);
            else if (underlineErrorItem.getSelection())
                setStyle(UNDERLINE_ERROR);
            else if (underlineSquiggleItem.getSelection())
                setStyle(UNDERLINE_SQUIGGLE);
        }
    }));

    ToolItem strikeoutControl = new ToolItem(styleToolBar, SWT.DROP_DOWN);
    strikeoutControl.setImage(iStrikeout);
    strikeoutControl.setToolTipText(getResourceString("Strikeout")); //$NON-NLS-1$
    strikeoutControl.addSelectionListener(widgetSelectedAdapter(event -> {
        if (event.detail == SWT.ARROW) {
            ColorDialog dialog = new ColorDialog(shell);
            RGB rgb = strikeoutColor != null ? strikeoutColor.getRGB() : null;
            dialog.setRGB(rgb);
            RGB newRgb = dialog.open();
            if (newRgb == null)
                return;
            if (!newRgb.equals(rgb)) {
                disposeResource(strikeoutColor);
                strikeoutColor = new Color(display, newRgb);
            }
        }
        setStyle(STRIKEOUT);
    }));

    final Menu borderMenu = new Menu(shell, SWT.POP_UP);
    borderSolidItem = new MenuItem(borderMenu, SWT.RADIO);
    borderSolidItem.setText(getResourceString("Solid")); //$NON-NLS-1$
    borderSolidItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (borderSolidItem.getSelection()) {
            setStyle(BORDER_SOLID);
        }
    }));
    borderSolidItem.setSelection(true);

    borderDashItem = new MenuItem(borderMenu, SWT.RADIO);
    borderDashItem.setText(getResourceString("Dash")); //$NON-NLS-1$
    borderDashItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (borderDashItem.getSelection()) {
            setStyle(BORDER_DASH);
        }
    }));

    borderDotItem = new MenuItem(borderMenu, SWT.RADIO);
    borderDotItem.setText(getResourceString("Dot")); //$NON-NLS-1$
    borderDotItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (borderDotItem.getSelection()) {
            setStyle(BORDER_DOT);
        }
    }));

    MenuItem borderColorItem = new MenuItem(borderMenu, SWT.PUSH);
    borderColorItem.setText(getResourceString("Color_menuitem")); //$NON-NLS-1$
    borderColorItem.addSelectionListener(widgetSelectedAdapter(event -> {
        ColorDialog dialog = new ColorDialog(shell);
        RGB rgb = borderColor != null ? borderColor.getRGB() : null;
        dialog.setRGB(rgb);
        RGB newRgb = dialog.open();
        if (newRgb != null) {
            if (!newRgb.equals(rgb)) {
                disposeResource(borderColor);
                borderColor = new Color(display, newRgb);
            }
            if (borderDashItem.getSelection())
                setStyle(BORDER_DASH);
            else if (borderDotItem.getSelection())
                setStyle(BORDER_DOT);
            else if (borderSolidItem.getSelection())
                setStyle(BORDER_SOLID);
        }
    }));

    final ToolItem borderControl = new ToolItem(styleToolBar, SWT.DROP_DOWN);
    borderControl.setImage(iBorderStyle);
    borderControl.setToolTipText(getResourceString("Box")); //$NON-NLS-1$
    borderControl.addSelectionListener(widgetSelectedAdapter(event -> {
        if (event.detail == SWT.ARROW) {
            Rectangle rect = borderControl.getBounds();
            Point pt = new Point(rect.x, rect.y + rect.height);
            borderMenu.setLocation(display.map(borderControl.getParent(), null, pt));
            borderMenu.setVisible(true);
        } else {
            if (borderDashItem.getSelection())
                setStyle(BORDER_DASH);
            else if (borderDotItem.getSelection())
                setStyle(BORDER_DOT);
            else if (borderSolidItem.getSelection())
                setStyle(BORDER_SOLID);
        }
    }));

    ToolItem foregroundItem = new ToolItem(styleToolBar, SWT.DROP_DOWN);
    foregroundItem.setImage(iTextForeground);
    foregroundItem.setToolTipText(getResourceString("TextForeground")); //$NON-NLS-1$
    foregroundItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (event.detail == SWT.ARROW || textForeground == null) {
            ColorDialog dialog = new ColorDialog(shell);
            RGB rgb = textForeground != null ? textForeground.getRGB() : null;
            dialog.setRGB(rgb);
            RGB newRgb = dialog.open();
            if (newRgb == null)
                return;
            if (!newRgb.equals(rgb)) {
                disposeResource(textForeground);
                textForeground = new Color(display, newRgb);
            }
        }
        setStyle(FOREGROUND);
    }));

    ToolItem backgroundItem = new ToolItem(styleToolBar, SWT.DROP_DOWN);
    backgroundItem.setImage(iTextBackground);
    backgroundItem.setToolTipText(getResourceString("TextBackground")); //$NON-NLS-1$
    backgroundItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (event.detail == SWT.ARROW || textBackground == null) {
            ColorDialog dialog = new ColorDialog(shell);
            RGB rgb = textBackground != null ? textBackground.getRGB() : null;
            dialog.setRGB(rgb);
            RGB newRgb = dialog.open();
            if (newRgb == null)
                return;
            if (!newRgb.equals(rgb)) {
                disposeResource(textBackground);
                textBackground = new Color(display, newRgb);
            }
        }
        setStyle(BACKGROUND);
    }));

    ToolItem baselineUpItem = new ToolItem(styleToolBar, SWT.PUSH);
    baselineUpItem.setImage(iBaselineUp);
    String tooltip = "IncreaseFont"; //$NON-NLS-1$
    if (USE_BASELINE)
        tooltip = "IncreaseBaseline"; //$NON-NLS-1$
    baselineUpItem.setToolTipText(getResourceString(tooltip));
    baselineUpItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (USE_BASELINE) {
            setStyle(BASELINE_UP);
        } else {
            adjustFontSize(1);
        }
    }));

    ToolItem baselineDownItem = new ToolItem(styleToolBar, SWT.PUSH);
    baselineDownItem.setImage(iBaselineDown);
    tooltip = "DecreaseFont"; //$NON-NLS-1$
    if (USE_BASELINE)
        tooltip = "DecreaseBaseline"; //$NON-NLS-1$
    baselineDownItem.setToolTipText(getResourceString(tooltip));
    baselineDownItem.addSelectionListener(widgetSelectedAdapter(event -> {
        if (USE_BASELINE) {
            setStyle(BASELINE_DOWN);
        } else {
            adjustFontSize(-1);
        }
    }));
    ToolItem linkItem = new ToolItem(styleToolBar, SWT.PUSH);
    linkItem.setImage(iLink);
    linkItem.setToolTipText(getResourceString("Link")); //$NON-NLS-1$
    linkItem.addSelectionListener(widgetSelectedAdapter(event -> setLink()));

    CoolItem coolItem = new CoolItem(coolBar, SWT.NONE);
    coolItem.setControl(styleToolBar);

    Composite composite = new Composite(coolBar, SWT.NONE);
    GridLayout layout = new GridLayout(2, false);
    layout.marginHeight = 1;
    composite.setLayout(layout);
    fontNameControl = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
    fontNameControl.setItems(getFontNames());
    fontNameControl.setVisibleItemCount(12);
    fontSizeControl = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
    fontSizeControl.setItems(FONT_SIZES);
    fontSizeControl.setVisibleItemCount(8);
    SelectionListener adapter = widgetSelectedAdapter(event -> {
        String name = fontNameControl.getText();
        int size = Integer.parseInt(fontSizeControl.getText());
        disposeResource(textFont);
        textFont = new Font(display, name, size, SWT.NORMAL);
        setStyle(FONT);
    });
    fontSizeControl.addSelectionListener(adapter);
    fontNameControl.addSelectionListener(adapter);
    coolItem = new CoolItem(coolBar, SWT.NONE);
    coolItem.setControl(composite);

    ToolBar alignmentToolBar = new ToolBar(coolBar, SWT.FLAT);
    blockSelectionItem = new ToolItem(alignmentToolBar, SWT.CHECK);
    blockSelectionItem.setImage(iBlockSelection);
    blockSelectionItem.setToolTipText(getResourceString("BlockSelection")); //$NON-NLS-1$
    blockSelectionItem.addSelectionListener(
            widgetSelectedAdapter(event -> styledText.invokeAction(ST.TOGGLE_BLOCKSELECTION)));

    leftAlignmentItem = new ToolItem(alignmentToolBar, SWT.RADIO);
    leftAlignmentItem.setImage(iLeftAlignment);
    leftAlignmentItem.setToolTipText(getResourceString("AlignLeft")); //$NON-NLS-1$
    leftAlignmentItem.setSelection(true);
    leftAlignmentItem.addSelectionListener(widgetSelectedAdapter(event -> {
        Point selection = styledText.getSelection();
        int lineStart = styledText.getLineAtOffset(selection.x);
        int lineEnd = styledText.getLineAtOffset(selection.y);
        styledText.setLineAlignment(lineStart, lineEnd - lineStart + 1, SWT.LEFT);
    }));
    leftAlignmentItem.setEnabled(false);

    centerAlignmentItem = new ToolItem(alignmentToolBar, SWT.RADIO);
    centerAlignmentItem.setImage(iCenterAlignment);
    centerAlignmentItem.setToolTipText(getResourceString("Center_menuitem")); //$NON-NLS-1$
    centerAlignmentItem.addSelectionListener(widgetSelectedAdapter(event -> {
        Point selection = styledText.getSelection();
        int lineStart = styledText.getLineAtOffset(selection.x);
        int lineEnd = styledText.getLineAtOffset(selection.y);
        styledText.setLineAlignment(lineStart, lineEnd - lineStart + 1, SWT.CENTER);
    }));
    centerAlignmentItem.setEnabled(false);

    rightAlignmentItem = new ToolItem(alignmentToolBar, SWT.RADIO);
    rightAlignmentItem.setImage(iRightAlignment);
    rightAlignmentItem.setToolTipText(getResourceString("AlignRight")); //$NON-NLS-1$
    rightAlignmentItem.addSelectionListener(widgetSelectedAdapter(event -> {
        Point selection = styledText.getSelection();
        int lineStart = styledText.getLineAtOffset(selection.x);
        int lineEnd = styledText.getLineAtOffset(selection.y);
        styledText.setLineAlignment(lineStart, lineEnd - lineStart + 1, SWT.RIGHT);
    }));
    rightAlignmentItem.setEnabled(false);

    justifyAlignmentItem = new ToolItem(alignmentToolBar, SWT.CHECK);
    justifyAlignmentItem.setImage(iJustifyAlignment);
    justifyAlignmentItem.setToolTipText(getResourceString("Justify")); //$NON-NLS-1$
    justifyAlignmentItem.addSelectionListener(widgetSelectedAdapter(event -> {
        Point selection = styledText.getSelection();
        int lineStart = styledText.getLineAtOffset(selection.x);
        int lineEnd = styledText.getLineAtOffset(selection.y);
        styledText.setLineJustify(lineStart, lineEnd - lineStart + 1, justifyAlignmentItem.getSelection());
    }));
    justifyAlignmentItem.setEnabled(false);

    ToolItem bulletListItem = new ToolItem(alignmentToolBar, SWT.PUSH);
    bulletListItem.setImage(iBulletList);
    bulletListItem.setToolTipText(getResourceString("BulletList")); //$NON-NLS-1$
    bulletListItem.addSelectionListener(widgetSelectedAdapter(event -> setBullet(ST.BULLET_DOT)));

    ToolItem numberedListItem = new ToolItem(alignmentToolBar, SWT.PUSH);
    numberedListItem.setImage(iNumberedList);
    numberedListItem.setToolTipText(getResourceString("NumberedList")); //$NON-NLS-1$
    numberedListItem
            .addSelectionListener(widgetSelectedAdapter(event -> setBullet(ST.BULLET_NUMBER | ST.BULLET_TEXT)));

    coolItem = new CoolItem(coolBar, SWT.NONE);
    coolItem.setControl(alignmentToolBar);
    composite = new Composite(coolBar, SWT.NONE);
    layout = new GridLayout(4, false);
    layout.marginHeight = 1;
    composite.setLayout(layout);
    Label label = new Label(composite, SWT.NONE);
    label.setText(getResourceString("Indent")); //$NON-NLS-1$
    Spinner indent = new Spinner(composite, SWT.BORDER);
    indent.addSelectionListener(widgetSelectedAdapter(event -> {
        Spinner spinner = (Spinner) event.widget;
        styledText.setIndent(spinner.getSelection());
    }));
    label = new Label(composite, SWT.NONE);
    label.setText(getResourceString("Spacing")); //$NON-NLS-1$
    Spinner spacing = new Spinner(composite, SWT.BORDER);
    spacing.addSelectionListener(widgetSelectedAdapter(event -> {
        Spinner spinner = (Spinner) event.widget;
        styledText.setLineSpacing(spinner.getSelection());
    }));

    coolItem = new CoolItem(coolBar, SWT.NONE);
    coolItem.setControl(composite);

    // Button to toggle Mouse Navigator in StyledText
    composite = new Composite(coolBar, SWT.NONE);
    composite.setLayout(new GridLayout(1, false));
    Button mouseNavigator = new Button(composite, SWT.CHECK);
    mouseNavigator.setText(getResourceString("MouseNav"));
    mouseNavigator.addSelectionListener(
            widgetSelectedAdapter(event -> styledText.setMouseNavigatorEnabled(mouseNavigator.getSelection())));
    coolItem = new CoolItem(coolBar, SWT.NONE);
    coolItem.setControl(composite);

    // Compute Size for various CoolItems
    CoolItem[] coolItems = coolBar.getItems();
    for (CoolItem item : coolItems) {
        Control control = item.getControl();
        Point size = control.computeSize(SWT.DEFAULT, SWT.DEFAULT);
        item.setMinimumSize(size);
        size = item.computeSize(size.x, size.y);
        item.setPreferredSize(size);
        item.setSize(size);
    }

    coolBar.addControlListener(ControlListener.controlResizedAdapter(event -> handleResize(event)));
}

From source file:SWTFileViewerDemo.java

/**
 * Creates the file details table./*from w w w . ja  va  2  s.  c  o m*/
 * 
 * @param parent
 *            the parent control
 */
private void createTableView(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 1;
    gridLayout.marginHeight = gridLayout.marginWidth = 2;
    gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
    composite.setLayout(gridLayout);
    tableContentsOfLabel = new Label(composite, SWT.BORDER);
    tableContentsOfLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));

    table = new Table(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
    table.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));

    for (int i = 0; i < tableTitles.length; ++i) {
        TableColumn column = new TableColumn(table, SWT.NONE);
        column.setText(tableTitles[i]);
        column.setWidth(tableWidths[i]);
    }
    table.setHeaderVisible(true);
    table.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            notifySelectedFiles(getSelectedFiles());
        }

        public void widgetDefaultSelected(SelectionEvent event) {
            doDefaultFileAction(getSelectedFiles());
        }

        private File[] getSelectedFiles() {
            final TableItem[] items = table.getSelection();
            final File[] files = new File[items.length];

            for (int i = 0; i < items.length; ++i) {
                files[i] = (File) items[i].getData(TABLEITEMDATA_FILE);
            }
            return files;
        }
    });

    createTableDragSource(table);
    createTableDropTarget(table);
}

From source file:SWTFileViewerDemo.java

/**
 * Creates the file tree view.//from   w ww .ja  va  2s .  c  o  m
 * 
 * @param parent
 *            the parent control
 */
private void createTreeView(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 1;
    gridLayout.marginHeight = gridLayout.marginWidth = 2;
    gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
    composite.setLayout(gridLayout);

    treeScopeLabel = new Label(composite, SWT.BORDER);
    treeScopeLabel.setText(SWTFileViewerDemo.getResourceString("details.AllFolders.text"));
    treeScopeLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));

    tree = new Tree(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE);
    tree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));

    tree.addSelectionListener(new SelectionListener() {
        public void widgetSelected(SelectionEvent event) {
            final TreeItem[] selection = tree.getSelection();
            if (selection != null && selection.length != 0) {
                TreeItem item = selection[0];
                File file = (File) item.getData(TREEITEMDATA_FILE);

                notifySelectedDirectory(file);
            }
        }

        public void widgetDefaultSelected(SelectionEvent event) {
            final TreeItem[] selection = tree.getSelection();
            if (selection != null && selection.length != 0) {
                TreeItem item = selection[0];
                item.setExpanded(true);
                treeExpandItem(item);
            }
        }
    });
    tree.addTreeListener(new TreeAdapter() {
        public void treeExpanded(TreeEvent event) {
            final TreeItem item = (TreeItem) event.item;
            final Image image = (Image) item.getData(TREEITEMDATA_IMAGEEXPANDED);
            if (image != null)
                item.setImage(image);
            treeExpandItem(item);
        }

        public void treeCollapsed(TreeEvent event) {
            final TreeItem item = (TreeItem) event.item;
            final Image image = (Image) item.getData(TREEITEMDATA_IMAGECOLLAPSED);
            if (image != null)
                item.setImage(image);
        }
    });
    createTreeDragSource(tree);
    createTreeDropTarget(tree);
}

From source file:ImageAnalyzer.java

void createWidgets() {
    // Add the widgets to the shell in a grid layout.
    GridLayout layout = new GridLayout();
    layout.marginHeight = 0;/*from ww w .  j  av a 2s. c  om*/
    layout.numColumns = 2;
    shell.setLayout(layout);

    // Separate the menu bar from the rest of the widgets.
    Label separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    GridData gridData = new GridData();
    gridData.horizontalSpan = 2;
    gridData.horizontalAlignment = GridData.FILL;
    separator.setLayoutData(gridData);

    // Add a composite to contain some control widgets across the top.
    Composite controls = new Composite(shell, SWT.NULL);
    RowLayout rowLayout = new RowLayout();
    rowLayout.marginTop = 0;
    rowLayout.marginBottom = 5;
    rowLayout.spacing = 8;
    controls.setLayout(rowLayout);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    controls.setLayoutData(gridData);

    // Combo to change the background.
    Group group = new Group(controls, SWT.NULL);
    group.setLayout(new RowLayout());
    group.setText("Background");
    backgroundCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
    backgroundCombo.setItems(new String[] { "None", "White", "Black", "Red", "Green", "Blue" });
    backgroundCombo.select(backgroundCombo.indexOf("White"));
    backgroundCombo.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            changeBackground();
        }
    });

    // Combo to change the x scale.
    String[] values = { "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1", "1.1", "1.2", "1.3",
            "1.4", "1.5", "1.6", "1.7", "1.8", "1.9", "2", "3", "4", "5", "6", "7", "8", "9", "10", };
    group = new Group(controls, SWT.NULL);
    group.setLayout(new RowLayout());
    group.setText("X_scale");
    scaleXCombo = new Combo(group, SWT.DROP_DOWN);
    for (int i = 0; i < values.length; i++) {
        scaleXCombo.add(values[i]);
    }
    scaleXCombo.select(scaleXCombo.indexOf("1"));
    scaleXCombo.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            scaleX();
        }
    });

    // Combo to change the y scale.
    group = new Group(controls, SWT.NULL);
    group.setLayout(new RowLayout());
    group.setText("Y_scale");
    scaleYCombo = new Combo(group, SWT.DROP_DOWN);
    for (int i = 0; i < values.length; i++) {
        scaleYCombo.add(values[i]);
    }
    scaleYCombo.select(scaleYCombo.indexOf("1"));
    scaleYCombo.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            scaleY();
        }
    });

    // Combo to change the alpha value.
    group = new Group(controls, SWT.NULL);
    group.setLayout(new RowLayout());
    group.setText("Alpha_K");
    alphaCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
    for (int i = 0; i <= 255; i += 5) {
        alphaCombo.add(String.valueOf(i));
    }
    alphaCombo.select(alphaCombo.indexOf("255"));
    alphaCombo.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            alpha();
        }
    });

    // Check box to request incremental display.
    group = new Group(controls, SWT.NULL);
    group.setLayout(new RowLayout());
    group.setText("Display");
    incrementalCheck = new Button(group, SWT.CHECK);
    incrementalCheck.setText("Incremental");
    incrementalCheck.setSelection(incremental);
    incrementalCheck.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            incremental = ((Button) event.widget).getSelection();
        }
    });

    // Check box to request transparent display.
    transparentCheck = new Button(group, SWT.CHECK);
    transparentCheck.setText("Transparent");
    transparentCheck.setSelection(transparent);
    transparentCheck.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            transparent = ((Button) event.widget).getSelection();
            if (image != null) {
                imageCanvas.redraw();
            }
        }
    });

    // Check box to request mask display.
    maskCheck = new Button(group, SWT.CHECK);
    maskCheck.setText("Mask");
    maskCheck.setSelection(showMask);
    maskCheck.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            showMask = ((Button) event.widget).getSelection();
            if (image != null) {
                imageCanvas.redraw();
            }
        }
    });

    // Check box to request background display.
    backgroundCheck = new Button(group, SWT.CHECK);
    backgroundCheck.setText("Background");
    backgroundCheck.setSelection(showBackground);
    backgroundCheck.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            showBackground = ((Button) event.widget).getSelection();
        }
    });

    // Group the animation buttons.
    group = new Group(controls, SWT.NULL);
    group.setLayout(new RowLayout());
    group.setText("Animation");

    // Push button to display the previous image in a multi-image file.
    previousButton = new Button(group, SWT.PUSH);
    previousButton.setText("Previous");
    previousButton.setEnabled(false);
    previousButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            previous();
        }
    });

    // Push button to display the next image in a multi-image file.
    nextButton = new Button(group, SWT.PUSH);
    nextButton.setText("Next");
    nextButton.setEnabled(false);
    nextButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            next();
        }
    });

    // Push button to toggle animation of a multi-image file.
    animateButton = new Button(group, SWT.PUSH);
    animateButton.setText("Animate");
    animateButton.setEnabled(false);
    animateButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            animate();
        }
    });

    // Label to show the image file type.
    typeLabel = new Label(shell, SWT.NULL);
    typeLabel.setText("Type_initial");
    typeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Canvas to show the image.
    imageCanvas = new Canvas(shell, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_REDRAW_RESIZE);
    imageCanvas.setBackground(whiteColor);
    imageCanvas.setCursor(crossCursor);
    gridData = new GridData();
    gridData.verticalSpan = 15;
    gridData.horizontalAlignment = GridData.FILL;
    gridData.verticalAlignment = GridData.FILL;
    gridData.grabExcessHorizontalSpace = true;
    gridData.grabExcessVerticalSpace = true;
    imageCanvas.setLayoutData(gridData);
    imageCanvas.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent event) {
            if (image != null)
                paintImage(event);
        }
    });
    imageCanvas.addMouseMoveListener(new MouseMoveListener() {
        public void mouseMove(MouseEvent event) {
            if (image != null) {
                showColorAt(event.x, event.y);
            }
        }
    });

    // Set up the image canvas scroll bars.
    ScrollBar horizontal = imageCanvas.getHorizontalBar();
    horizontal.setVisible(true);
    horizontal.setMinimum(0);
    horizontal.setEnabled(false);
    horizontal.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            scrollHorizontally((ScrollBar) event.widget);
        }
    });
    ScrollBar vertical = imageCanvas.getVerticalBar();
    vertical.setVisible(true);
    vertical.setMinimum(0);
    vertical.setEnabled(false);
    vertical.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            scrollVertically((ScrollBar) event.widget);
        }
    });

    // Label to show the image size.
    sizeLabel = new Label(shell, SWT.NULL);
    sizeLabel.setText("Size_initial");
    sizeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the image depth.
    depthLabel = new Label(shell, SWT.NULL);
    depthLabel.setText("Depth_initial");
    depthLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the transparent pixel.
    transparentPixelLabel = new Label(shell, SWT.NULL);
    transparentPixelLabel.setText("Transparent_pixel_initial");
    transparentPixelLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the time to load.
    timeToLoadLabel = new Label(shell, SWT.NULL);
    timeToLoadLabel.setText("Time_to_load_initial");
    timeToLoadLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Separate the animation fields from the rest of the fields.
    separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    separator.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the logical screen size for animation.
    screenSizeLabel = new Label(shell, SWT.NULL);
    screenSizeLabel.setText("Animation_size_initial");
    screenSizeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the background pixel.
    backgroundPixelLabel = new Label(shell, SWT.NULL);
    backgroundPixelLabel.setText("Background_pixel_initial");
    backgroundPixelLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the image location (x, y).
    locationLabel = new Label(shell, SWT.NULL);
    locationLabel.setText("Image_location_initial");
    locationLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the image disposal method.
    disposalMethodLabel = new Label(shell, SWT.NULL);
    disposalMethodLabel.setText("Disposal_initial");
    disposalMethodLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the image delay time.
    delayTimeLabel = new Label(shell, SWT.NULL);
    delayTimeLabel.setText("Delay_initial");
    delayTimeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the background pixel.
    repeatCountLabel = new Label(shell, SWT.NULL);
    repeatCountLabel.setText("Repeats_initial");
    repeatCountLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Separate the animation fields from the palette.
    separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    separator.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show if the image has a direct or indexed palette.
    paletteLabel = new Label(shell, SWT.NULL);
    paletteLabel.setText("Palette_initial");
    paletteLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Canvas to show the image's palette.
    paletteCanvas = new Canvas(shell, SWT.BORDER | SWT.V_SCROLL | SWT.NO_REDRAW_RESIZE);
    paletteCanvas.setFont(fixedWidthFont);
    paletteCanvas.getVerticalBar().setVisible(true);
    gridData = new GridData();
    gridData.horizontalAlignment = GridData.FILL;
    gridData.verticalAlignment = GridData.FILL;
    GC gc = new GC(paletteLabel);
    paletteWidth = gc.stringExtent("Max_length_string").x;
    gc.dispose();
    gridData.widthHint = paletteWidth;
    gridData.heightHint = 16 * 11; // show at least 16 colors
    paletteCanvas.setLayoutData(gridData);
    paletteCanvas.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent event) {
            if (image != null)
                paintPalette(event);
        }
    });

    // Set up the palette canvas scroll bar.
    vertical = paletteCanvas.getVerticalBar();
    vertical.setVisible(true);
    vertical.setMinimum(0);
    vertical.setIncrement(10);
    vertical.setEnabled(false);
    vertical.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            scrollPalette((ScrollBar) event.widget);
        }
    });

    // Sash to see more of image or image data.
    sash = new Sash(shell, SWT.HORIZONTAL);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    gridData.horizontalAlignment = GridData.FILL;
    sash.setLayoutData(gridData);
    sash.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            if (event.detail != SWT.DRAG) {
                ((GridData) paletteCanvas.getLayoutData()).heightHint = SWT.DEFAULT;
                Rectangle paletteCanvasBounds = paletteCanvas.getBounds();
                int minY = paletteCanvasBounds.y + 20;
                Rectangle dataLabelBounds = dataLabel.getBounds();
                int maxY = statusLabel.getBounds().y - dataLabelBounds.height - 20;
                if (event.y > minY && event.y < maxY) {
                    Rectangle oldSash = sash.getBounds();
                    sash.setBounds(event.x, event.y, event.width, event.height);
                    int diff = event.y - oldSash.y;
                    Rectangle bounds = imageCanvas.getBounds();
                    imageCanvas.setBounds(bounds.x, bounds.y, bounds.width, bounds.height + diff);
                    bounds = paletteCanvasBounds;
                    paletteCanvas.setBounds(bounds.x, bounds.y, bounds.width, bounds.height + diff);
                    bounds = dataLabelBounds;
                    dataLabel.setBounds(bounds.x, bounds.y + diff, bounds.width, bounds.height);
                    bounds = dataText.getBounds();
                    dataText.setBounds(bounds.x, bounds.y + diff, bounds.width, bounds.height - diff);
                    // shell.layout(true);
                }
            }
        }
    });

    // Label to show data-specific fields.
    dataLabel = new Label(shell, SWT.NULL);
    dataLabel.setText("Pixel_data_initial");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    gridData.horizontalAlignment = GridData.FILL;
    dataLabel.setLayoutData(gridData);

    // Text to show a dump of the data.
    dataText = new StyledText(shell, SWT.BORDER | SWT.MULTI | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);
    dataText.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
    dataText.setFont(fixedWidthFont);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    gridData.horizontalAlignment = GridData.FILL;
    gridData.verticalAlignment = GridData.FILL;
    gridData.heightHint = 128;
    gridData.grabExcessVerticalSpace = true;
    dataText.setLayoutData(gridData);
    dataText.addMouseListener(new MouseAdapter() {
        public void mouseDown(MouseEvent event) {
            if (image != null && event.button == 1) {
                showColorForData();
            }
        }
    });
    dataText.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent event) {
            if (image != null) {
                showColorForData();
            }
        }
    });

    // Label to show status and cursor location in image.
    statusLabel = new Label(shell, SWT.NULL);
    statusLabel.setText("");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    gridData.horizontalAlignment = GridData.FILL;
    statusLabel.setLayoutData(gridData);
}

From source file:org.eclipse.swt.examples.imageanalyzer.ImageAnalyzer.java

void createWidgets() {
    // Add the widgets to the shell in a grid layout.
    GridLayout layout = new GridLayout();
    layout.marginHeight = 0;/*ww w. jav a 2  s  .com*/
    layout.numColumns = 2;
    shell.setLayout(layout);

    // Add a composite to contain some control widgets across the top.
    Composite controls = new Composite(shell, SWT.NONE);
    RowLayout rowLayout = new RowLayout();
    rowLayout.marginTop = 5;
    rowLayout.marginBottom = 5;
    rowLayout.spacing = 8;
    controls.setLayout(rowLayout);
    GridData gridData = new GridData();
    gridData.horizontalSpan = 2;
    controls.setLayoutData(gridData);

    // Combo to change the background.
    Group group = new Group(controls, SWT.NONE);
    group.setLayout(new RowLayout());
    group.setText(bundle.getString("Background"));
    backgroundCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
    backgroundCombo.setItems(bundle.getString("None"), bundle.getString("White"), bundle.getString("Black"),
            bundle.getString("Red"), bundle.getString("Green"), bundle.getString("Blue"));
    backgroundCombo.select(backgroundCombo.indexOf(bundle.getString("White")));
    backgroundCombo.addSelectionListener(widgetSelectedAdapter(event -> changeBackground()));

    // Combo to change the compression ratio.
    group = new Group(controls, SWT.NONE);
    group.setLayout(new GridLayout(3, true));
    group.setText(bundle.getString("Save_group"));
    imageTypeCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
    String[] types = { "JPEG", "PNG", "GIF", "ICO", "TIFF", "BMP" };
    for (String type : types) {
        imageTypeCombo.add(type);
    }
    imageTypeCombo.select(imageTypeCombo.indexOf("JPEG"));
    imageTypeCombo.addSelectionListener(widgetSelectedAdapter(event -> {
        int index = imageTypeCombo.getSelectionIndex();
        switch (index) {
        case 0:
            compressionCombo.setEnabled(true);
            compressionRatioLabel.setEnabled(true);
            if (compressionCombo.getItemCount() == 100)
                break;
            compressionCombo.removeAll();
            for (int i = 0; i < 100; i++) {
                compressionCombo.add(String.valueOf(i + 1));
            }
            compressionCombo.select(compressionCombo.indexOf("75"));
            break;
        case 1:
            compressionCombo.setEnabled(true);
            compressionRatioLabel.setEnabled(true);
            if (compressionCombo.getItemCount() == 10)
                break;
            compressionCombo.removeAll();
            for (int i = 0; i < 4; i++) {
                compressionCombo.add(String.valueOf(i));
            }
            compressionCombo.select(0);
            break;
        case 2:
        case 3:
        case 4:
        case 5:
            compressionCombo.setEnabled(false);
            compressionRatioLabel.setEnabled(false);
            break;
        }
    }));
    imageTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    compressionRatioLabel = new Label(group, SWT.NONE);
    compressionRatioLabel.setText(bundle.getString("Compression"));
    compressionRatioLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
    compressionCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
    for (int i = 0; i < 100; i++) {
        compressionCombo.add(String.valueOf(i + 1));
    }
    compressionCombo.select(compressionCombo.indexOf("75"));
    compressionCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    // Combo to change the x scale.
    String[] values = { "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1", "1.1", "1.2", "1.3",
            "1.4", "1.5", "1.6", "1.7", "1.8", "1.9", "2", "3", "4", "5", "6", "7", "8", "9", "10", };
    group = new Group(controls, SWT.NONE);
    group.setLayout(new RowLayout());
    group.setText(bundle.getString("X_scale"));
    scaleXCombo = new Combo(group, SWT.DROP_DOWN);
    for (String value : values) {
        scaleXCombo.add(value);
    }
    scaleXCombo.select(scaleXCombo.indexOf("1"));
    scaleXCombo.addSelectionListener(widgetSelectedAdapter(event -> scaleX()));

    // Combo to change the y scale.
    group = new Group(controls, SWT.NONE);
    group.setLayout(new RowLayout());
    group.setText(bundle.getString("Y_scale"));
    scaleYCombo = new Combo(group, SWT.DROP_DOWN);
    for (String value : values) {
        scaleYCombo.add(value);
    }
    scaleYCombo.select(scaleYCombo.indexOf("1"));
    scaleYCombo.addSelectionListener(widgetSelectedAdapter(event -> scaleY()));

    // Combo to change the alpha value.
    group = new Group(controls, SWT.NONE);
    group.setLayout(new RowLayout());
    group.setText(bundle.getString("Alpha_K"));
    alphaCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
    for (int i = 0; i <= 255; i += 5) {
        alphaCombo.add(String.valueOf(i));
    }
    alphaCombo.select(alphaCombo.indexOf("255"));
    alphaCombo.addSelectionListener(widgetSelectedAdapter(event -> alpha()));

    // Check box to request incremental display.
    group = new Group(controls, SWT.NONE);
    group.setLayout(new RowLayout());
    group.setText(bundle.getString("Display"));
    incrementalCheck = new Button(group, SWT.CHECK);
    incrementalCheck.setText(bundle.getString("Incremental"));
    incrementalCheck.setSelection(incremental);
    incrementalCheck.addSelectionListener(
            widgetSelectedAdapter(event -> incremental = ((Button) event.widget).getSelection()));

    // Check box to request transparent display.
    transparentCheck = new Button(group, SWT.CHECK);
    transparentCheck.setText(bundle.getString("Transparent"));
    transparentCheck.setSelection(transparent);
    transparentCheck.addSelectionListener(widgetSelectedAdapter(event -> {
        transparent = ((Button) event.widget).getSelection();
        if (image != null) {
            imageCanvas.redraw();
        }
    }));

    // Check box to request mask display.
    maskCheck = new Button(group, SWT.CHECK);
    maskCheck.setText(bundle.getString("Mask"));
    maskCheck.setSelection(showMask);
    maskCheck.addSelectionListener(widgetSelectedAdapter(event -> {
        showMask = ((Button) event.widget).getSelection();
        if (image != null) {
            imageCanvas.redraw();
        }
    }));

    // Check box to request background display.
    backgroundCheck = new Button(group, SWT.CHECK);
    backgroundCheck.setText(bundle.getString("Background"));
    backgroundCheck.setSelection(showBackground);
    backgroundCheck.addSelectionListener(
            widgetSelectedAdapter(event -> showBackground = ((Button) event.widget).getSelection()));

    // Group the animation buttons.
    group = new Group(controls, SWT.NONE);
    group.setLayout(new RowLayout());
    group.setText(bundle.getString("Animation"));

    // Push button to display the previous image in a multi-image file.
    previousButton = new Button(group, SWT.PUSH);
    previousButton.setText(bundle.getString("Previous"));
    previousButton.setEnabled(false);
    previousButton.addSelectionListener(widgetSelectedAdapter(event -> previous()));

    // Push button to display the next image in a multi-image file.
    nextButton = new Button(group, SWT.PUSH);
    nextButton.setText(bundle.getString("Next"));
    nextButton.setEnabled(false);
    nextButton.addSelectionListener(widgetSelectedAdapter(event -> next()));

    // Push button to toggle animation of a multi-image file.
    animateButton = new Button(group, SWT.PUSH);
    animateButton.setText(bundle.getString("Animate"));
    animateButton.setEnabled(false);
    animateButton.addSelectionListener(widgetSelectedAdapter(event -> animate()));

    // Label to show the image file type.
    typeLabel = new Label(shell, SWT.NONE);
    typeLabel.setText(bundle.getString("Type_initial"));
    typeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Canvas to show the image.
    imageCanvas = new Canvas(shell, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_REDRAW_RESIZE | SWT.NO_BACKGROUND);
    imageCanvas.setBackground(whiteColor);
    imageCanvas.setCursor(crossCursor);
    gridData = new GridData();
    gridData.verticalSpan = 15;
    gridData.horizontalAlignment = GridData.FILL;
    gridData.verticalAlignment = GridData.FILL;
    gridData.grabExcessHorizontalSpace = true;
    gridData.grabExcessVerticalSpace = true;
    imageCanvas.setLayoutData(gridData);
    imageCanvas.addPaintListener(event -> {
        if (image == null) {
            Rectangle bounds = imageCanvas.getBounds();
            event.gc.fillRectangle(0, 0, bounds.width, bounds.height);
        } else {
            paintImage(event);
        }
    });
    imageCanvas.addMouseMoveListener(event -> {
        if (image != null) {
            showColorAt(event.x, event.y);
        }
    });

    // Set up the image canvas scroll bars.
    ScrollBar horizontal = imageCanvas.getHorizontalBar();
    horizontal.setVisible(true);
    horizontal.setMinimum(0);
    horizontal.setEnabled(false);
    horizontal
            .addSelectionListener(widgetSelectedAdapter(event -> scrollHorizontally((ScrollBar) event.widget)));
    ScrollBar vertical = imageCanvas.getVerticalBar();
    vertical.setVisible(true);
    vertical.setMinimum(0);
    vertical.setEnabled(false);
    vertical.addSelectionListener(widgetSelectedAdapter(event -> scrollVertically((ScrollBar) event.widget)));

    // Label to show the image size.
    sizeLabel = new Label(shell, SWT.NONE);
    sizeLabel.setText(bundle.getString("Size_initial"));
    sizeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the image depth.
    depthLabel = new Label(shell, SWT.NONE);
    depthLabel.setText(bundle.getString("Depth_initial"));
    depthLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the transparent pixel.
    transparentPixelLabel = new Label(shell, SWT.NONE);
    transparentPixelLabel.setText(bundle.getString("Transparent_pixel_initial"));
    transparentPixelLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the time to load.
    timeToLoadLabel = new Label(shell, SWT.NONE);
    timeToLoadLabel.setText(bundle.getString("Time_to_load_initial"));
    timeToLoadLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Separate the animation fields from the rest of the fields.
    Label separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    separator.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the logical screen size for animation.
    screenSizeLabel = new Label(shell, SWT.NONE);
    screenSizeLabel.setText(bundle.getString("Animation_size_initial"));
    screenSizeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the background pixel.
    backgroundPixelLabel = new Label(shell, SWT.NONE);
    backgroundPixelLabel.setText(bundle.getString("Background_pixel_initial"));
    backgroundPixelLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the image location (x, y).
    locationLabel = new Label(shell, SWT.NONE);
    locationLabel.setText(bundle.getString("Image_location_initial"));
    locationLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the image disposal method.
    disposalMethodLabel = new Label(shell, SWT.NONE);
    disposalMethodLabel.setText(bundle.getString("Disposal_initial"));
    disposalMethodLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the image delay time.
    delayTimeLabel = new Label(shell, SWT.NONE);
    delayTimeLabel.setText(bundle.getString("Delay_initial"));
    delayTimeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show the background pixel.
    repeatCountLabel = new Label(shell, SWT.NONE);
    repeatCountLabel.setText(bundle.getString("Repeats_initial"));
    repeatCountLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Separate the animation fields from the palette.
    separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    separator.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Label to show if the image has a direct or indexed palette.
    paletteLabel = new Label(shell, SWT.NONE);
    paletteLabel.setText(bundle.getString("Palette_initial"));
    paletteLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    // Canvas to show the image's palette.
    paletteCanvas = new Canvas(shell, SWT.BORDER | SWT.V_SCROLL | SWT.NO_REDRAW_RESIZE);
    paletteCanvas.setFont(fixedWidthFont);
    paletteCanvas.getVerticalBar().setVisible(true);
    gridData = new GridData();
    gridData.horizontalAlignment = GridData.FILL;
    gridData.verticalAlignment = GridData.FILL;
    GC gc = new GC(paletteLabel);
    paletteWidth = gc.stringExtent(bundle.getString("Max_length_string")).x;
    gc.dispose();
    gridData.widthHint = paletteWidth;
    gridData.heightHint = 16 * 11; // show at least 16 colors
    paletteCanvas.setLayoutData(gridData);
    paletteCanvas.addPaintListener(event -> {
        if (image != null)
            paintPalette(event);
    });

    // Set up the palette canvas scroll bar.
    vertical = paletteCanvas.getVerticalBar();
    vertical.setVisible(true);
    vertical.setMinimum(0);
    vertical.setIncrement(10);
    vertical.setEnabled(false);
    vertical.addSelectionListener(widgetSelectedAdapter(event -> scrollPalette((ScrollBar) event.widget)));

    // Sash to see more of image or image data.
    sash = new Sash(shell, SWT.HORIZONTAL);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    gridData.horizontalAlignment = GridData.FILL;
    sash.setLayoutData(gridData);
    sash.addSelectionListener(widgetSelectedAdapter(event -> {
        if (event.detail != SWT.DRAG) {
            ((GridData) paletteCanvas.getLayoutData()).heightHint = SWT.DEFAULT;
            Rectangle paletteCanvasBounds = paletteCanvas.getBounds();
            int minY = paletteCanvasBounds.y + 20;
            Rectangle dataLabelBounds = dataLabel.getBounds();
            int maxY = statusLabel.getBounds().y - dataLabelBounds.height - 20;
            if (event.y > minY && event.y < maxY) {
                Rectangle oldSash = sash.getBounds();
                sash.setBounds(event.x, event.y, event.width, event.height);
                int diff = event.y - oldSash.y;
                Rectangle bounds = imageCanvas.getBounds();
                imageCanvas.setBounds(bounds.x, bounds.y, bounds.width, bounds.height + diff);
                bounds = paletteCanvasBounds;
                paletteCanvas.setBounds(bounds.x, bounds.y, bounds.width, bounds.height + diff);
                bounds = dataLabelBounds;
                dataLabel.setBounds(bounds.x, bounds.y + diff, bounds.width, bounds.height);
                bounds = dataText.getBounds();
                dataText.setBounds(bounds.x, bounds.y + diff, bounds.width, bounds.height - diff);
                //shell.layout(true);
            }
        }
    }));

    // Label to show data-specific fields.
    dataLabel = new Label(shell, SWT.NONE);
    dataLabel.setText(bundle.getString("Pixel_data_initial"));
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    gridData.horizontalAlignment = GridData.FILL;
    dataLabel.setLayoutData(gridData);

    // Text to show a dump of the data.
    dataText = new StyledText(shell, SWT.BORDER | SWT.MULTI | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);
    dataText.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
    dataText.setFont(fixedWidthFont);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    gridData.horizontalAlignment = GridData.FILL;
    gridData.verticalAlignment = GridData.FILL;
    gridData.heightHint = 128;
    gridData.grabExcessVerticalSpace = true;
    dataText.setLayoutData(gridData);
    dataText.addMouseListener(MouseListener.mouseDownAdapter(event -> {
        if (image != null && event.button == 1) {
            showColorForData();
        }
    }));
    dataText.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent event) {
            if (image != null) {
                showColorForData();
            }
        }
    });

    // Label to show status and cursor location in image.
    statusLabel = new Label(shell, SWT.NONE);
    statusLabel.setText("");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    gridData.horizontalAlignment = GridData.FILL;
    statusLabel.setLayoutData(gridData);
}

From source file:PaintExample.java

/**
 * Handles a mouseDown event./*from ww  w  . ja v  a  2 s .c  o m*/
 * 
 * @param event the mouse event detail information
 */
public void mouseDown(MouseEvent event) {
    if (event.button == 1) {
        // draw with left mouse button
        getPaintSurface().commitRubberbandSelection();
    } else {
        // set text with right mouse button
        getPaintSurface().clearRubberbandSelection();
        Shell shell = getPaintSurface().getShell();
        final Shell dialog = new Shell(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
        dialog.setText(PaintExample.getResourceString("tool.Text.dialog.title"));
        dialog.setLayout(new GridLayout());
        Label label = new Label(dialog, SWT.NONE);
        label.setText(PaintExample.getResourceString("tool.Text.dialog.message"));
        label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
        final Text field = new Text(dialog, SWT.SINGLE | SWT.BORDER);
        field.setText(drawText);
        field.selectAll();
        field.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        Composite buttons = new Composite(dialog, SWT.NONE);
        GridLayout layout = new GridLayout(2, true);
        layout.marginWidth = 0;
        buttons.setLayout(layout);
        buttons.setLayoutData(new GridData(SWT.END, SWT.CENTER, false, false));
        Button ok = new Button(buttons, SWT.PUSH);
        ok.setText(PaintExample.getResourceString("OK"));
        ok.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
        ok.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                drawText = field.getText();
                dialog.dispose();
            }
        });
        Button cancel = new Button(buttons, SWT.PUSH);
        cancel.setText(PaintExample.getResourceString("Cancel"));
        cancel.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                dialog.dispose();
            }
        });
        dialog.setDefaultButton(ok);
        dialog.pack();
        dialog.open();
        Display display = dialog.getDisplay();
        while (!shell.isDisposed() && !dialog.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
    }
}

From source file:PaintExample.java

/**
 * Creates the GUI.//from   w ww.  ja va 2s .  com
 */
public void createGUI(Composite parent) {
    GridLayout gridLayout;
    GridData gridData;

    /*** Create principal GUI layout elements ***/
    Composite displayArea = new Composite(parent, SWT.NONE);
    gridLayout = new GridLayout();
    gridLayout.numColumns = 1;
    displayArea.setLayout(gridLayout);

    // Creating these elements here avoids the need to instantiate the GUI elements
    // in strict layout order.  The natural layout ordering is an artifact of using
    // SWT layouts, but unfortunately it is not the same order as that required to
    // instantiate all of the non-GUI application elements to satisfy referential
    // dependencies.  It is possible to reorder the initialization to some extent, but
    // this can be very tedious.

    // paint canvas
    final Canvas paintCanvas = new Canvas(displayArea,
            SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_REDRAW_RESIZE | SWT.NO_BACKGROUND);
    gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
    paintCanvas.setLayoutData(gridData);
    paintCanvas.setBackground(paintColorWhite);

    // color selector frame
    final Composite colorFrame = new Composite(displayArea, SWT.NONE);
    gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
    colorFrame.setLayoutData(gridData);

    // tool settings frame
    final Composite toolSettingsFrame = new Composite(displayArea, SWT.NONE);
    gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
    toolSettingsFrame.setLayoutData(gridData);

    // status text
    final Text statusText = new Text(displayArea, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY);
    gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
    statusText.setLayoutData(gridData);

    /*** Create the remaining application elements inside the principal GUI layout elements ***/
    // paintSurface
    paintSurface = new PaintSurface(paintCanvas, statusText, paintColorWhite);

    // finish initializing the tool data
    tools[Pencil_tool].data = new PencilTool(toolSettings, paintSurface);
    tools[Airbrush_tool].data = new AirbrushTool(toolSettings, paintSurface);
    tools[Line_tool].data = new LineTool(toolSettings, paintSurface);
    tools[PolyLine_tool].data = new PolyLineTool(toolSettings, paintSurface);
    tools[Rectangle_tool].data = new RectangleTool(toolSettings, paintSurface);
    tools[RoundedRectangle_tool].data = new RoundedRectangleTool(toolSettings, paintSurface);
    tools[Ellipse_tool].data = new EllipseTool(toolSettings, paintSurface);
    tools[Text_tool].data = new TextTool(toolSettings, paintSurface);

    // colorFrame      
    gridLayout = new GridLayout();
    gridLayout.numColumns = 3;
    gridLayout.marginHeight = 0;
    gridLayout.marginWidth = 0;
    colorFrame.setLayout(gridLayout);

    // activeForegroundColorCanvas, activeBackgroundColorCanvas
    activeForegroundColorCanvas = new Canvas(colorFrame, SWT.BORDER);
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    gridData.heightHint = 24;
    gridData.widthHint = 24;
    activeForegroundColorCanvas.setLayoutData(gridData);

    activeBackgroundColorCanvas = new Canvas(colorFrame, SWT.BORDER);
    gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    gridData.heightHint = 24;
    gridData.widthHint = 24;
    activeBackgroundColorCanvas.setLayoutData(gridData);

    // paletteCanvas
    final Canvas paletteCanvas = new Canvas(colorFrame, SWT.BORDER | SWT.NO_BACKGROUND);
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.heightHint = 24;
    paletteCanvas.setLayoutData(gridData);
    paletteCanvas.addListener(SWT.MouseDown, new Listener() {
        public void handleEvent(Event e) {
            Rectangle bounds = paletteCanvas.getClientArea();
            Color color = getColorAt(bounds, e.x, e.y);

            if (e.button == 1)
                setForegroundColor(color);
            else
                setBackgroundColor(color);
        }

        private Color getColorAt(Rectangle bounds, int x, int y) {
            if (bounds.height <= 1 && bounds.width <= 1)
                return paintColorWhite;
            final int row = (y - bounds.y) * numPaletteRows / bounds.height;
            final int col = (x - bounds.x) * numPaletteCols / bounds.width;
            return paintColors[Math.min(Math.max(row * numPaletteCols + col, 0), paintColors.length - 1)];
        }
    });
    Listener refreshListener = new Listener() {
        public void handleEvent(Event e) {
            if (e.gc == null)
                return;
            Rectangle bounds = paletteCanvas.getClientArea();
            for (int row = 0; row < numPaletteRows; ++row) {
                for (int col = 0; col < numPaletteCols; ++col) {
                    final int x = bounds.width * col / numPaletteCols;
                    final int y = bounds.height * row / numPaletteRows;
                    final int width = Math.max(bounds.width * (col + 1) / numPaletteCols - x, 1);
                    final int height = Math.max(bounds.height * (row + 1) / numPaletteRows - y, 1);
                    e.gc.setBackground(paintColors[row * numPaletteCols + col]);
                    e.gc.fillRectangle(bounds.x + x, bounds.y + y, width, height);
                }
            }
        }
    };
    paletteCanvas.addListener(SWT.Resize, refreshListener);
    paletteCanvas.addListener(SWT.Paint, refreshListener);
    //paletteCanvas.redraw();

    // toolSettingsFrame
    gridLayout = new GridLayout();
    gridLayout.numColumns = 4;
    gridLayout.marginHeight = 0;
    gridLayout.marginWidth = 0;
    toolSettingsFrame.setLayout(gridLayout);

    Label label = new Label(toolSettingsFrame, SWT.NONE);
    label.setText(getResourceString("settings.AirbrushRadius.text"));

    final Scale airbrushRadiusScale = new Scale(toolSettingsFrame, SWT.HORIZONTAL);
    airbrushRadiusScale.setMinimum(5);
    airbrushRadiusScale.setMaximum(50);
    airbrushRadiusScale.setSelection(toolSettings.airbrushRadius);
    airbrushRadiusScale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
    airbrushRadiusScale.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            toolSettings.airbrushRadius = airbrushRadiusScale.getSelection();
            updateToolSettings();
        }
    });

    label = new Label(toolSettingsFrame, SWT.NONE);
    label.setText(getResourceString("settings.AirbrushIntensity.text"));

    final Scale airbrushIntensityScale = new Scale(toolSettingsFrame, SWT.HORIZONTAL);
    airbrushIntensityScale.setMinimum(1);
    airbrushIntensityScale.setMaximum(100);
    airbrushIntensityScale.setSelection(toolSettings.airbrushIntensity);
    airbrushIntensityScale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
    airbrushIntensityScale.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            toolSettings.airbrushIntensity = airbrushIntensityScale.getSelection();
            updateToolSettings();
        }
    });
}