Example usage for org.eclipse.swt.widgets Canvas Canvas

List of usage examples for org.eclipse.swt.widgets Canvas Canvas

Introduction

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

Prototype

public Canvas(Composite parent, int style) 

Source Link

Document

Constructs a new instance of this class given its parent and a style value describing its behavior and appearance.

Usage

From source file:org.eclipse.swt.examples.browserexample.BrowserExample.java

void show(boolean owned, Point location, Point size, boolean addressBar, boolean menuBar, boolean statusBar,
        boolean toolBar) {
    final Shell shell = browser.getShell();
    if (owned) {/*from   w  w w . ja  v  a  2  s  .c om*/
        if (location != null)
            shell.setLocation(location);
        if (size != null)
            shell.setSize(shell.computeSize(size.x, size.y));
    }
    FormData data = null;
    if (toolBar) {
        toolbar = new ToolBar(parent, SWT.NONE);
        data = new FormData();
        data.top = new FormAttachment(0, 5);
        toolbar.setLayoutData(data);
        itemBack = new ToolItem(toolbar, SWT.PUSH);
        itemBack.setText(getResourceString("Back"));
        itemForward = new ToolItem(toolbar, SWT.PUSH);
        itemForward.setText(getResourceString("Forward"));
        final ToolItem itemStop = new ToolItem(toolbar, SWT.PUSH);
        itemStop.setText(getResourceString("Stop"));
        final ToolItem itemRefresh = new ToolItem(toolbar, SWT.PUSH);
        itemRefresh.setText(getResourceString("Refresh"));
        final ToolItem itemGo = new ToolItem(toolbar, SWT.PUSH);
        itemGo.setText(getResourceString("Go"));

        itemBack.setEnabled(browser.isBackEnabled());
        itemForward.setEnabled(browser.isForwardEnabled());
        Listener listener = event -> {
            ToolItem item = (ToolItem) event.widget;
            if (item == itemBack)
                browser.back();
            else if (item == itemForward)
                browser.forward();
            else if (item == itemStop)
                browser.stop();
            else if (item == itemRefresh)
                browser.refresh();
            else if (item == itemGo)
                browser.setUrl(locationBar.getText());
        };
        itemBack.addListener(SWT.Selection, listener);
        itemForward.addListener(SWT.Selection, listener);
        itemStop.addListener(SWT.Selection, listener);
        itemRefresh.addListener(SWT.Selection, listener);
        itemGo.addListener(SWT.Selection, listener);

        canvas = new Canvas(parent, SWT.NO_BACKGROUND);
        data = new FormData();
        data.width = 24;
        data.height = 24;
        data.top = new FormAttachment(0, 5);
        data.right = new FormAttachment(100, -5);
        canvas.setLayoutData(data);

        final Rectangle rect = images[0].getBounds();
        canvas.addListener(SWT.Paint, e -> {
            Point pt = ((Canvas) e.widget).getSize();
            e.gc.drawImage(images[index], 0, 0, rect.width, rect.height, 0, 0, pt.x, pt.y);
        });
        canvas.addListener(SWT.MouseDown, e -> browser.setUrl(getResourceString("Startup")));

        final Display display = parent.getDisplay();
        display.asyncExec(new Runnable() {
            @Override
            public void run() {
                if (canvas.isDisposed())
                    return;
                if (busy) {
                    index++;
                    if (index == images.length)
                        index = 0;
                    canvas.redraw();
                }
                display.timerExec(150, this);
            }
        });
    }
    if (addressBar) {
        locationBar = new Text(parent, SWT.BORDER);
        data = new FormData();
        if (toolbar != null) {
            data.top = new FormAttachment(toolbar, 0, SWT.TOP);
            data.left = new FormAttachment(toolbar, 5, SWT.RIGHT);
            data.right = new FormAttachment(canvas, -5, SWT.DEFAULT);
        } else {
            data.top = new FormAttachment(0, 0);
            data.left = new FormAttachment(0, 0);
            data.right = new FormAttachment(100, 0);
        }
        locationBar.setLayoutData(data);
        locationBar.addListener(SWT.DefaultSelection, e -> browser.setUrl(locationBar.getText()));
    }
    if (statusBar) {
        status = new Label(parent, SWT.NONE);
        progressBar = new ProgressBar(parent, SWT.NONE);

        data = new FormData();
        data.left = new FormAttachment(0, 5);
        data.right = new FormAttachment(progressBar, 0, SWT.DEFAULT);
        data.bottom = new FormAttachment(100, -5);
        status.setLayoutData(data);

        data = new FormData();
        data.right = new FormAttachment(100, -5);
        data.bottom = new FormAttachment(100, -5);
        progressBar.setLayoutData(data);

        browser.addStatusTextListener(event -> status.setText(event.text));
    }
    parent.setLayout(new FormLayout());

    Control aboveBrowser = toolBar ? (Control) canvas : (addressBar ? (Control) locationBar : null);
    data = new FormData();
    data.left = new FormAttachment(0, 0);
    data.top = aboveBrowser != null ? new FormAttachment(aboveBrowser, 5, SWT.DEFAULT)
            : new FormAttachment(0, 0);
    data.right = new FormAttachment(100, 0);
    data.bottom = status != null ? new FormAttachment(status, -5, SWT.DEFAULT) : new FormAttachment(100, 0);
    browser.setLayoutData(data);

    if (statusBar || toolBar) {
        browser.addProgressListener(new ProgressListener() {
            @Override
            public void changed(ProgressEvent event) {
                if (event.total == 0)
                    return;
                int ratio = event.current * 100 / event.total;
                if (progressBar != null)
                    progressBar.setSelection(ratio);
                busy = event.current != event.total;
                if (!busy) {
                    index = 0;
                    if (canvas != null)
                        canvas.redraw();
                }
            }

            @Override
            public void completed(ProgressEvent event) {
                if (progressBar != null)
                    progressBar.setSelection(0);
                busy = false;
                index = 0;
                if (canvas != null) {
                    itemBack.setEnabled(browser.isBackEnabled());
                    itemForward.setEnabled(browser.isForwardEnabled());
                    canvas.redraw();
                }
            }
        });
    }
    if (addressBar || statusBar || toolBar) {
        browser.addLocationListener(LocationListener.changedAdapter(event -> {
            busy = true;
            if (event.top && locationBar != null)
                locationBar.setText(event.location);
        }));
    }
    if (title) {
        browser.addTitleListener(
                event -> shell.setText(event.title + " - " + getResourceString("window.title")));
    }
    parent.layout(true);
    if (owned)
        shell.open();
}

From source file:SWTBrowserDemo.java

void show(boolean owned, Point location, Point size, boolean addressBar, boolean menuBar, boolean statusBar,
        boolean toolBar) {
    final Shell shell = browser.getShell();
    if (owned) {/* ww w.jav  a  2 s  . c o m*/
        if (location != null)
            shell.setLocation(location);
        if (size != null)
            shell.setSize(shell.computeSize(size.x, size.y));
    }
    FormData data = null;
    if (toolBar) {
        toolbar = new ToolBar(parent, SWT.NONE);
        data = new FormData();
        data.top = new FormAttachment(0, 5);
        toolbar.setLayoutData(data);
        itemBack = new ToolItem(toolbar, SWT.PUSH);
        itemBack.setText(getResourceString("Back"));
        itemForward = new ToolItem(toolbar, SWT.PUSH);
        itemForward.setText(getResourceString("Forward"));
        final ToolItem itemStop = new ToolItem(toolbar, SWT.PUSH);
        itemStop.setText(getResourceString("Stop"));
        final ToolItem itemRefresh = new ToolItem(toolbar, SWT.PUSH);
        itemRefresh.setText(getResourceString("Refresh"));
        final ToolItem itemGo = new ToolItem(toolbar, SWT.PUSH);
        itemGo.setText(getResourceString("Go"));

        itemBack.setEnabled(browser.isBackEnabled());
        itemForward.setEnabled(browser.isForwardEnabled());
        Listener listener = new Listener() {
            public void handleEvent(Event event) {
                ToolItem item = (ToolItem) event.widget;
                if (item == itemBack)
                    browser.back();
                else if (item == itemForward)
                    browser.forward();
                else if (item == itemStop)
                    browser.stop();
                else if (item == itemRefresh)
                    browser.refresh();
                else if (item == itemGo)
                    browser.setUrl(locationBar.getText());
            }
        };
        itemBack.addListener(SWT.Selection, listener);
        itemForward.addListener(SWT.Selection, listener);
        itemStop.addListener(SWT.Selection, listener);
        itemRefresh.addListener(SWT.Selection, listener);
        itemGo.addListener(SWT.Selection, listener);

        canvas = new Canvas(parent, SWT.NO_BACKGROUND);
        data = new FormData();
        data.width = 24;
        data.height = 24;
        data.top = new FormAttachment(0, 5);
        data.right = new FormAttachment(100, -5);
        canvas.setLayoutData(data);

        final Rectangle rect = images[0].getBounds();
        canvas.addListener(SWT.Paint, new Listener() {
            public void handleEvent(Event e) {
                Point pt = ((Canvas) e.widget).getSize();
                e.gc.drawImage(images[index], 0, 0, rect.width, rect.height, 0, 0, pt.x, pt.y);
            }
        });
        canvas.addListener(SWT.MouseDown, new Listener() {
            public void handleEvent(Event e) {
                browser.setUrl(getResourceString("Startup"));
            }
        });

        final Display display = parent.getDisplay();
        display.asyncExec(new Runnable() {
            public void run() {
                if (canvas.isDisposed())
                    return;
                if (busy) {
                    index++;
                    if (index == images.length)
                        index = 0;
                    canvas.redraw();
                }
                display.timerExec(150, this);
            }
        });
    }
    if (addressBar) {
        locationBar = new Text(parent, SWT.BORDER);
        data = new FormData();
        if (toolbar != null) {
            data.top = new FormAttachment(toolbar, 0, SWT.TOP);
            data.left = new FormAttachment(toolbar, 5, SWT.RIGHT);
            data.right = new FormAttachment(canvas, -5, SWT.DEFAULT);
        } else {
            data.top = new FormAttachment(0, 0);
            data.left = new FormAttachment(0, 0);
            data.right = new FormAttachment(100, 0);
        }
        locationBar.setLayoutData(data);
        locationBar.addListener(SWT.DefaultSelection, new Listener() {
            public void handleEvent(Event e) {
                browser.setUrl(locationBar.getText());
            }
        });
    }
    if (statusBar) {
        status = new Label(parent, SWT.NONE);
        progressBar = new ProgressBar(parent, SWT.NONE);

        data = new FormData();
        data.left = new FormAttachment(0, 5);
        data.right = new FormAttachment(progressBar, 0, SWT.DEFAULT);
        data.bottom = new FormAttachment(100, -5);
        status.setLayoutData(data);

        data = new FormData();
        data.right = new FormAttachment(100, -5);
        data.bottom = new FormAttachment(100, -5);
        progressBar.setLayoutData(data);

        browser.addStatusTextListener(new StatusTextListener() {
            public void changed(StatusTextEvent event) {
                status.setText(event.text);
            }
        });
    }
    parent.setLayout(new FormLayout());

    Control aboveBrowser = toolBar ? (Control) canvas : (addressBar ? (Control) locationBar : null);
    data = new FormData();
    data.left = new FormAttachment(0, 0);
    data.top = aboveBrowser != null ? new FormAttachment(aboveBrowser, 5, SWT.DEFAULT)
            : new FormAttachment(0, 0);
    data.right = new FormAttachment(100, 0);
    data.bottom = status != null ? new FormAttachment(status, -5, SWT.DEFAULT) : new FormAttachment(100, 0);
    browser.setLayoutData(data);

    if (statusBar || toolBar) {
        browser.addProgressListener(new ProgressListener() {
            public void changed(ProgressEvent event) {
                if (event.total == 0)
                    return;
                int ratio = event.current * 100 / event.total;
                if (progressBar != null)
                    progressBar.setSelection(ratio);
                busy = event.current != event.total;
                if (!busy) {
                    index = 0;
                    if (canvas != null)
                        canvas.redraw();
                }
            }

            public void completed(ProgressEvent event) {
                if (progressBar != null)
                    progressBar.setSelection(0);
                busy = false;
                index = 0;
                if (canvas != null) {
                    itemBack.setEnabled(browser.isBackEnabled());
                    itemForward.setEnabled(browser.isForwardEnabled());
                    canvas.redraw();
                }
            }
        });
    }
    if (addressBar || statusBar || toolBar) {
        browser.addLocationListener(new LocationListener() {
            public void changed(LocationEvent event) {
                busy = true;
                if (event.top && locationBar != null)
                    locationBar.setText(event.location);
            }

            public void changing(LocationEvent event) {
            }
        });
    }
    if (title) {
        browser.addTitleListener(new TitleListener() {
            public void changed(TitleEvent event) {
                shell.setText(event.title + " - " + getResourceString("window.title"));
            }
        });
    }
    parent.layout(true);
    if (owned)
        shell.open();
}

From source file:org.pentaho.di.ui.spoon.trans.StepPerformanceSnapShotDialog.java

public void open() {

    shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
    props.setLook(shell);//  w  w  w .ja  va2s . c  om
    shell.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Title"));
    shell.setImage(GUIResource.getInstance().getImageLogoSmall());

    FormLayout formLayout = new FormLayout();
    formLayout.marginWidth = Const.FORM_MARGIN;
    formLayout.marginHeight = Const.FORM_MARGIN;

    shell.setLayout(formLayout);

    // Display 2 lists with the data types and the steps on the left side.
    // Then put a canvas with the graph on the right side
    //
    dataList = new org.eclipse.swt.widgets.List(shell,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    props.setLook(dataList);
    dataList.setItems(dataChoices);
    dataList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the steps list, we only take the
            // first step in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                stepsList.setSelection(stepsList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });
    FormData fdDataList = new FormData();
    fdDataList.left = new FormAttachment(0, 0);
    fdDataList.right = new FormAttachment(props.getMiddlePct() / 2, Const.MARGIN);
    fdDataList.top = new FormAttachment(0, 0);
    fdDataList.bottom = new FormAttachment(30, 0);
    dataList.setLayoutData(fdDataList);

    stepsList = new org.eclipse.swt.widgets.List(shell,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    props.setLook(stepsList);
    stepsList.setItems(steps);
    stepsList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the data list, we only take the
            // first data item in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                dataList.setSelection(dataList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });
    FormData fdStepsList = new FormData();
    fdStepsList.left = new FormAttachment(0, 0);
    fdStepsList.right = new FormAttachment(props.getMiddlePct() / 2, Const.MARGIN);
    fdStepsList.top = new FormAttachment(dataList, Const.MARGIN);
    fdStepsList.bottom = new FormAttachment(100, Const.MARGIN);
    stepsList.setLayoutData(fdStepsList);

    canvas = new Canvas(shell, SWT.NONE);
    props.setLook(canvas);
    FormData fdCanvas = new FormData();
    fdCanvas.left = new FormAttachment(props.getMiddlePct() / 2, 0);
    fdCanvas.right = new FormAttachment(100, 0);
    fdCanvas.top = new FormAttachment(0, 0);
    fdCanvas.bottom = new FormAttachment(100, 0);
    canvas.setLayoutData(fdCanvas);

    shell.addControlListener(new ControlAdapter() {
        public void controlResized(ControlEvent event) {
            updateGraph();
        }
    });

    shell.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent event) {
            if (image != null) {
                image.dispose();
            }
        }
    });

    canvas.addPaintListener(new PaintListener() {

        public void paintControl(PaintEvent event) {
            if (image != null) {
                event.gc.drawImage(image, 0, 0);
            }
        }
    });

    // Refresh automatically every 5 seconds as well.
    //
    Timer timer = new Timer("step performance snapshot dialog Timer");
    timer.schedule(new TimerTask() {
        public void run() {
            updateGraph();
        }
    }, 0, 5000);

    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
}

From source file:org.eclipse.swt.examples.graphics.GraphicsExample.java

void createCanvas(Composite parent) {
    int style = SWT.NO_BACKGROUND;
    if (dbItem.getSelection())
        style |= SWT.DOUBLE_BUFFERED;/*  www.jav a 2s .c  o  m*/
    canvas = new Canvas(parent, style);
    canvas.addListener(SWT.Paint, event -> {
        GC gc = event.gc;
        Rectangle rect = canvas.getClientArea();
        Device device = gc.getDevice();
        Pattern pattern = null;
        if (background.getBgColor1() != null) {
            if (background.getBgColor2() != null) { // gradient
                pattern = new Pattern(device, 0, 0, rect.width, rect.height, background.getBgColor1(),
                        background.getBgColor2());
                gc.setBackgroundPattern(pattern);
            } else { // solid color
                gc.setBackground(background.getBgColor1());
            }
        } else if (background.getBgImage() != null) { // image
            pattern = new Pattern(device, background.getBgImage());
            gc.setBackgroundPattern(pattern);
        }
        gc.fillRectangle(rect);
        GraphicsTab tab = getTab();
        if (tab != null)
            tab.paint(gc, rect.width, rect.height);
        if (pattern != null)
            pattern.dispose();
    });
}

From source file:ClassFigure.java

protected Control createContents(Composite parent) {
    Composite composite = new Composite(parent, SWT.NULL);
    composite.setLayout(new FillLayout());

    canvas = new Canvas(composite, SWT.NULL);
    canvas.setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_WHITE));

    LightweightSystem lws = new LightweightSystem(canvas);
    contents = new Figure();
    xyLayout = new XYLayout();
    contents.setLayoutManager(xyLayout);

    lws.setContents(contents);//from w w w . ja v a 2 s  .c om

    showClass(this.getClass());

    // Creates tool bar items.
    getToolBarManager().add(new Action("Set class ...") {
        public void run() {
            InputDialog dialog = new InputDialog(getShell(), "", "Please enter the class name", "", null);
            if (dialog.open() != Dialog.OK)
                return;

            contents.removeAll();
            Class cls = null;
            try {
                cls = Class.forName(dialog.getValue());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (cls != null) {
                showClass(cls);
            }
        }
    });
    getToolBarManager().update(true);

    return composite;
}

From source file:org.eclipse.swt.examples.accessibility.ControlsWithAccessibleNamesExample.java

public static void main(String[] args) {
    display = new Display();
    shell = new Shell(display);
    shell.setLayout(new GridLayout(4, true));
    shell.setText("Override Accessibility Test");

    largeImage = new Image(display,
            ControlsWithAccessibleNamesExample.class.getResourceAsStream("run_wiz.gif"));
    smallImage = new Image(display, ControlsWithAccessibleNamesExample.class.getResourceAsStream("run.gif"));
    ImageData source = smallImage.getImageData();
    ImageData mask = source.getTransparencyMask();
    transparentImage = new Image(display, source, mask);

    new Label(shell, SWT.NONE).setText("Use Platform Name");
    new Label(shell, SWT.NONE).setText("Override Platform Name");
    new Label(shell, SWT.NONE).setText("Use Platform Name");
    new Label(shell, SWT.NONE).setText("Override Platform Name");

    AccessibleAdapter overrideAccessibleAdapter = new AccessibleAdapter() {
        @Override//from  ww  w  .j a v  a  2  s . c o m
        public void getName(AccessibleEvent e) {
            Control control = ((Accessible) e.getSource()).getControl();
            if (e.childID == ACC.CHILDID_SELF) {
                e.result = "Overriding Platform Name For " + control.getData("name") + " (was " + e.result
                        + ")";
            } else {
                e.result = "Overriding Platform Name For " + control.getData("child") + ": " + e.childID
                        + " (was " + e.result + ")";
            }
        }

        @Override
        public void getHelp(AccessibleEvent e) {
            Control control = ((Accessible) e.getSource()).getControl();
            if (e.childID == ACC.CHILDID_SELF) {
                e.result = "Overriding Platform Help For " + control.getData("name") + " (was " + e.result
                        + ")";
            } else {
                e.result = "Overriding Platform Help For " + control.getData("child") + ": " + e.childID
                        + " (was " + e.result + ")";
            }
        }
    };

    //      Shell shell;
    shell.setData("name", "Shell");
    shell.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Label label, overrideLabel;
    label = new Label(shell, SWT.BORDER);
    label.setText("Label");
    label.setToolTipText("Label ToolTip");

    overrideLabel = new Label(shell, SWT.BORDER);
    overrideLabel.setText("Label");
    overrideLabel.setToolTipText("Label ToolTip");
    overrideLabel.setData("name", "Label");
    overrideLabel.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Label imageLabel, overrideImageLabel;
    imageLabel = new Label(shell, SWT.BORDER);
    imageLabel.setImage(largeImage);
    imageLabel.setToolTipText("Image Label ToolTip");

    overrideImageLabel = new Label(shell, SWT.BORDER);
    overrideImageLabel.setImage(largeImage);
    overrideImageLabel.setToolTipText("Image Label ToolTip");
    overrideImageLabel.setData("name", "Image Label");
    overrideImageLabel.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Button button, overrideButton;
    button = new Button(shell, SWT.PUSH);
    button.setText("Button");
    button.setToolTipText("Button ToolTip");

    overrideButton = new Button(shell, SWT.PUSH);
    overrideButton.setText("Button");
    overrideButton.setToolTipText("Button ToolTip");
    overrideButton.setData("name", "Button");
    overrideButton.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Button imageButton, overrideImageButton;
    imageButton = new Button(shell, SWT.PUSH);
    imageButton.setImage(smallImage);
    imageButton.setToolTipText("Image Button ToolTip");

    overrideImageButton = new Button(shell, SWT.PUSH);
    overrideImageButton.setImage(smallImage);
    overrideImageButton.setToolTipText("Image Button ToolTip");
    overrideImageButton.setData("name", "Image Button");
    overrideImageButton.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Combo combo, overrideCombo;
    combo = new Combo(shell, SWT.BORDER);
    for (int i = 0; i < 5; i++) {
        combo.add("item" + i);
    }
    combo.setText("Combo");
    combo.setToolTipText("Combo ToolTip");

    overrideCombo = new Combo(shell, SWT.BORDER);
    for (int i = 0; i < 5; i++) {
        overrideCombo.add("item" + i);
    }
    overrideCombo.setText("Combo");
    overrideCombo.setToolTipText("Combo ToolTip");
    overrideCombo.setData("name", "Combo");
    overrideCombo.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Spinner spinner, overrideSpinner;
    spinner = new Spinner(shell, SWT.BORDER);
    spinner.setSelection(5);
    spinner.setToolTipText("Spinner ToolTip");

    overrideSpinner = new Spinner(shell, SWT.BORDER);
    overrideSpinner.setSelection(5);
    overrideSpinner.setToolTipText("Spinner ToolTip");
    overrideSpinner.setData("name", "Spinner");
    overrideSpinner.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Text text, overrideText;
    text = new Text(shell, SWT.SINGLE | SWT.BORDER);
    text.setText("Contents of single-line Text");

    overrideText = new Text(shell, SWT.SINGLE | SWT.BORDER);
    overrideText.setText("Contents of single-line Text");
    overrideText.setData("name", "Text");
    overrideText.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Text multiLineText, overrideMultiLineText;
    multiLineText = new Text(shell, SWT.MULTI | SWT.BORDER);
    multiLineText.setText("Contents of multi-line Text\nLine 2\nLine 3\nLine 4");

    overrideMultiLineText = new Text(shell, SWT.MULTI | SWT.BORDER);
    overrideMultiLineText.setText("Contents of multi-line Text\nLine 2\nLine 3\nLine 4");
    overrideMultiLineText.setData("name", "MultiLineText");
    overrideMultiLineText.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      List list, overrideList;
    list = new List(shell, SWT.SINGLE | SWT.BORDER);
    list.setItems("Item0", "Item1", "Item2");

    overrideList = new List(shell, SWT.SINGLE | SWT.BORDER);
    overrideList.setItems("Item0", "Item1", "Item2");
    overrideList.setData("name", "List");
    overrideList.setData("child", "List Item");
    overrideList.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Table table, overrideTable;
    table = new Table(shell, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
    table.setHeaderVisible(true);
    table.setLinesVisible(true);
    for (int col = 0; col < 3; col++) {
        TableColumn column = new TableColumn(table, SWT.NONE);
        column.setText("Col " + col);
        column.pack();
    }
    for (int row = 0; row < 3; row++) {
        TableItem item = new TableItem(table, SWT.NONE);
        item.setText(new String[] { "C0R" + row, "C1R" + row, "C2R" + row });
    }

    overrideTable = new Table(shell, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
    overrideTable.setHeaderVisible(true);
    overrideTable.setLinesVisible(true);
    for (int col = 0; col < 3; col++) {
        TableColumn column = new TableColumn(overrideTable, SWT.NONE);
        column.setText("Col " + col);
        column.pack();
    }
    for (int row = 0; row < 3; row++) {
        TableItem item = new TableItem(overrideTable, SWT.NONE);
        item.setText(new String[] { "C0R" + row, "C1R" + row, "C2R" + row });
    }
    overrideTable.setData("name", "Table");
    overrideTable.setData("child", "Table Item");
    overrideTable.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Tree tree, overrideTree;
    tree = new Tree(shell, SWT.BORDER | SWT.MULTI);
    for (int i = 0; i < 3; i++) {
        TreeItem item = new TreeItem(tree, SWT.NONE);
        item.setText("Item" + i);
        for (int j = 0; j < 4; j++) {
            new TreeItem(item, SWT.NONE).setText("Item" + i + j);
        }
    }

    overrideTree = new Tree(shell, SWT.BORDER | SWT.MULTI);
    for (int i = 0; i < 3; i++) {
        TreeItem item = new TreeItem(overrideTree, SWT.NONE);
        item.setText("Item" + i);
        for (int j = 0; j < 4; j++) {
            new TreeItem(item, SWT.NONE).setText("Item" + i + j);
        }
    }
    overrideTree.setData("name", "Tree");
    overrideTree.setData("child", "Tree Item");
    overrideTree.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Tree treeTable, overrideTreeTable;
    treeTable = new Tree(shell, SWT.BORDER | SWT.MULTI);
    treeTable.setHeaderVisible(true);
    treeTable.setLinesVisible(true);
    for (int col = 0; col < 3; col++) {
        TreeColumn column = new TreeColumn(treeTable, SWT.NONE);
        column.setText("Col " + col);
        column.pack();
    }
    for (int i = 0; i < 3; i++) {
        TreeItem item = new TreeItem(treeTable, SWT.NONE);
        item.setText(new String[] { "I" + i + "C0", "I" + i + "C1", "I" + i + "C2" });
        for (int j = 0; j < 4; j++) {
            new TreeItem(item, SWT.NONE)
                    .setText(new String[] { "I" + i + j + "C0", "I" + i + j + "C1", "I" + i + j + "C2" });
        }
    }

    overrideTreeTable = new Tree(shell, SWT.BORDER | SWT.MULTI);
    overrideTreeTable.setHeaderVisible(true);
    overrideTreeTable.setLinesVisible(true);
    for (int col = 0; col < 3; col++) {
        TreeColumn column = new TreeColumn(overrideTreeTable, SWT.NONE);
        column.setText("Col " + col);
        column.pack();
    }
    for (int i = 0; i < 3; i++) {
        TreeItem item = new TreeItem(overrideTreeTable, SWT.NONE);
        item.setText(new String[] { "I" + i + "C0", "I" + i + "C1", "I" + i + "C2" });
        for (int j = 0; j < 4; j++) {
            new TreeItem(item, SWT.NONE)
                    .setText(new String[] { "I" + i + j + "C0", "I" + i + j + "C1", "I" + i + j + "C2" });
        }
    }
    overrideTreeTable.setData("name", "Tree Table");
    overrideTreeTable.setData("child", "Tree Table Item");
    overrideTreeTable.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      ToolBar toolBar, overrideToolBar;
    toolBar = new ToolBar(shell, SWT.FLAT);
    for (int i = 0; i < 3; i++) {
        ToolItem item = new ToolItem(toolBar, SWT.PUSH);
        item.setText("Item" + i);
        item.setToolTipText("ToolItem ToolTip" + i);
    }

    overrideToolBar = new ToolBar(shell, SWT.FLAT);
    for (int i = 0; i < 3; i++) {
        ToolItem item = new ToolItem(overrideToolBar, SWT.PUSH);
        item.setText("Item" + i);
        item.setToolTipText("ToolItem ToolTip" + i);
    }
    overrideToolBar.setData("name", "ToolBar");
    overrideToolBar.setData("child", "ToolBar Item");
    overrideToolBar.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      ToolBar imageToolBar, overrideImageToolBar;
    imageToolBar = new ToolBar(shell, SWT.FLAT);
    for (int i = 0; i < 3; i++) {
        ToolItem item = new ToolItem(imageToolBar, SWT.PUSH);
        item.setImage(transparentImage);
        item.setToolTipText("Image ToolItem ToolTip" + i);
    }

    overrideImageToolBar = new ToolBar(shell, SWT.FLAT);
    for (int i = 0; i < 3; i++) {
        ToolItem item = new ToolItem(overrideImageToolBar, SWT.PUSH);
        item.setImage(transparentImage);
        item.setToolTipText("Image ToolItem ToolTip" + i);
    }
    overrideImageToolBar.setData("name", "Image ToolBar");
    overrideImageToolBar.setData("child", "Image ToolBar Item");
    overrideImageToolBar.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      CoolBar coolBar, overrideCoolBar;
    coolBar = new CoolBar(shell, SWT.FLAT);
    for (int i = 0; i < 2; i++) {
        CoolItem coolItem = new CoolItem(coolBar, SWT.PUSH);
        ToolBar coolItemToolBar = new ToolBar(coolBar, SWT.FLAT);
        int toolItemWidth = 0;
        for (int j = 0; j < 2; j++) {
            ToolItem item = new ToolItem(coolItemToolBar, SWT.PUSH);
            item.setText("I" + i + j);
            item.setToolTipText("ToolItem ToolTip" + i + j);
            if (item.getWidth() > toolItemWidth)
                toolItemWidth = item.getWidth();
        }
        coolItem.setControl(coolItemToolBar);
        Point size = coolItemToolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
        Point coolSize = coolItem.computeSize(size.x, size.y);
        coolItem.setMinimumSize(toolItemWidth, coolSize.y);
        coolItem.setPreferredSize(coolSize);
        coolItem.setSize(coolSize);
    }

    overrideCoolBar = new CoolBar(shell, SWT.FLAT);
    for (int i = 0; i < 2; i++) {
        CoolItem coolItem = new CoolItem(overrideCoolBar, SWT.PUSH);
        ToolBar coolItemToolBar = new ToolBar(overrideCoolBar, SWT.FLAT);
        int toolItemWidth = 0;
        for (int j = 0; j < 2; j++) {
            ToolItem item = new ToolItem(coolItemToolBar, SWT.PUSH);
            item.setText("I" + i + j);
            item.setToolTipText("ToolItem ToolTip" + i + j);
            if (item.getWidth() > toolItemWidth)
                toolItemWidth = item.getWidth();
        }
        coolItem.setControl(coolItemToolBar);
        Point size = coolItemToolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
        Point coolSize = coolItem.computeSize(size.x, size.y);
        coolItem.setMinimumSize(toolItemWidth, coolSize.y);
        coolItem.setPreferredSize(coolSize);
        coolItem.setSize(coolSize);
    }
    overrideCoolBar.setData("name", "CoolBar");
    overrideCoolBar.setData("child", "CoolBar Item");
    overrideCoolBar.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Canvas canvas, overrideCanvas;
    canvas = new Canvas(shell, SWT.BORDER);
    canvas.addPaintListener(e -> e.gc.drawString("Canvas", 15, 25));
    /* Set a caret into the canvas so that it will take focus. */
    Caret caret = new Caret(canvas, SWT.NONE);
    caret.setBounds(15, 25, 2, 20);
    canvas.setCaret(caret);
    /* Hook key listener so canvas will take focus during traversal in. */
    canvas.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            e.doit = true;
        }

        @Override
        public void keyReleased(KeyEvent e) {
            e.doit = true;
        }
    });
    /* Hook traverse listener to make canvas give up focus during traversal out. */
    canvas.addTraverseListener(e -> e.doit = true);

    overrideCanvas = new Canvas(shell, SWT.BORDER);
    overrideCanvas.addPaintListener(e -> e.gc.drawString("Canvas", 15, 25));
    /* Set a caret into the canvas so that it will take focus. */
    caret = new Caret(overrideCanvas, SWT.NONE);
    caret.setBounds(15, 25, 2, 20);
    overrideCanvas.setCaret(caret);
    /* Hook key listener so canvas will take focus during traversal in. */
    overrideCanvas.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            e.doit = true;
        }

        @Override
        public void keyReleased(KeyEvent e) {
            e.doit = true;
        }
    });
    /* Hook traverse listener to make canvas give up focus during traversal out. */
    overrideCanvas.addTraverseListener(e -> e.doit = true);
    overrideCanvas.setData("name", "Canvas");
    overrideCanvas.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Composite composite, overrideComposite;
    composite = new Composite(shell, SWT.BORDER);
    composite.setLayout(new GridLayout());
    new Button(composite, SWT.RADIO).setText("Child 1");
    new Button(composite, SWT.RADIO).setText("Child 2");

    overrideComposite = new Composite(shell, SWT.BORDER);
    overrideComposite.setLayout(new GridLayout());
    new Button(overrideComposite, SWT.RADIO).setText("Child 1");
    new Button(overrideComposite, SWT.RADIO).setText("Child 2");
    overrideComposite.setData("name", "Composite");
    overrideComposite.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Group group, overrideGroup;
    group = new Group(shell, SWT.NONE);
    group.setText("Group");
    group.setLayout(new FillLayout());
    new Text(group, SWT.SINGLE).setText("Text in Group");

    overrideGroup = new Group(shell, SWT.NONE);
    overrideGroup.setText("Group");
    overrideGroup.setLayout(new FillLayout());
    new Text(overrideGroup, SWT.SINGLE).setText("Text in Group");
    overrideGroup.setData("name", "Group");
    overrideGroup.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      TabFolder tabFolder, overrideTabFolder;
    tabFolder = new TabFolder(shell, SWT.NONE);
    for (int i = 0; i < 3; i++) {
        TabItem item = new TabItem(tabFolder, SWT.NONE);
        item.setText("TabItem &" + i);
        item.setToolTipText("TabItem ToolTip" + i);
        Text itemText = new Text(tabFolder, SWT.MULTI | SWT.BORDER);
        itemText.setText("\nText for TabItem " + i + "\n\n");
        item.setControl(itemText);
    }

    overrideTabFolder = new TabFolder(shell, SWT.NONE);
    for (int i = 0; i < 3; i++) {
        TabItem item = new TabItem(overrideTabFolder, SWT.NONE);
        item.setText("TabItem &" + i);
        item.setToolTipText("TabItem ToolTip" + i);
        Text itemText = new Text(overrideTabFolder, SWT.MULTI | SWT.BORDER);
        itemText.setText("\nText for TabItem " + i + "\n\n");
        item.setControl(itemText);
    }
    overrideTabFolder.setData("name", "TabFolder");
    overrideTabFolder.setData("child", "TabItem");
    overrideTabFolder.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      CLabel cLabel, overrideCLabel;
    cLabel = new CLabel(shell, SWT.BORDER);
    cLabel.setText("CLabel");
    cLabel.setToolTipText("CLabel ToolTip");
    cLabel.setLayoutData(new GridData(100, SWT.DEFAULT));

    overrideCLabel = new CLabel(shell, SWT.BORDER);
    overrideCLabel.setText("CLabel");
    overrideCLabel.setToolTipText("CLabel ToolTip");
    overrideCLabel.setLayoutData(new GridData(100, SWT.DEFAULT));
    overrideCLabel.setData("name", "CLabel");
    overrideCLabel.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      CCombo cCombo, overrideCCombo;
    cCombo = new CCombo(shell, SWT.BORDER);
    for (int i = 0; i < 5; i++) {
        cCombo.add("item" + i);
    }
    cCombo.setText("CCombo");
    cCombo.setToolTipText("CCombo ToolTip");

    // Note: This doesn't work well because CCombo has Control children
    overrideCCombo = new CCombo(shell, SWT.BORDER);
    for (int i = 0; i < 5; i++) {
        overrideCCombo.add("item" + i);
    }
    overrideCCombo.setText("CCombo");
    overrideCCombo.setToolTipText("CCombo ToolTip");
    overrideCCombo.setData("name", "CCombo");
    overrideCCombo.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      CTabFolder cTabFolder, overrideCTabFolder;
    cTabFolder = new CTabFolder(shell, SWT.NONE);
    for (int i = 0; i < 3; i++) {
        CTabItem item = new CTabItem(cTabFolder, SWT.NONE);
        item.setText("CTabItem &" + i);
        item.setToolTipText("TabItem ToolTip" + i);
        Text itemText = new Text(cTabFolder, SWT.MULTI | SWT.BORDER);
        itemText.setText("\nText for CTabItem " + i + "\n\n");
        item.setControl(itemText);
    }
    cTabFolder.setSelection(cTabFolder.getItem(0));

    overrideCTabFolder = new CTabFolder(shell, SWT.NONE);
    for (int i = 0; i < 3; i++) {
        CTabItem item = new CTabItem(overrideCTabFolder, SWT.NONE);
        item.setText("CTabItem &" + i);
        item.setToolTipText("TabItem ToolTip" + i);
        Text itemText = new Text(overrideCTabFolder, SWT.MULTI | SWT.BORDER);
        itemText.setText("\nText for CTabItem " + i + "\n\n");
        item.setControl(itemText);
    }
    overrideCTabFolder.setSelection(overrideCTabFolder.getItem(0));
    overrideCTabFolder.setData("name", "CTabFolder");
    overrideCTabFolder.setData("child", "CTabItem");
    overrideCTabFolder.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      StyledText styledText, overrideStyledText;
    styledText = new StyledText(shell, SWT.SINGLE | SWT.BORDER);
    styledText.setText("Contents of single-line StyledText");

    overrideStyledText = new StyledText(shell, SWT.SINGLE | SWT.BORDER);
    overrideStyledText.setText("Contents of single-line StyledText");
    overrideStyledText.setData("name", "StyledText");
    overrideStyledText.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      StyledText multiLineStyledText, overrideMultiLineStyledText;
    multiLineStyledText = new StyledText(shell, SWT.MULTI | SWT.BORDER);
    multiLineStyledText.setText("Contents of multi-line StyledText\nLine 2\nLine 3\nLine 4");

    overrideMultiLineStyledText = new StyledText(shell, SWT.MULTI | SWT.BORDER);
    overrideMultiLineStyledText.setText("Contents of multi-line StyledText\nLine 2\nLine 3\nLine 4");
    overrideMultiLineStyledText.setData("name", "MultiLineStyledText");
    overrideMultiLineStyledText.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Scale scale, overrideScale;
    scale = new Scale(shell, SWT.NONE);
    scale.setToolTipText("Scale ToolTip");

    overrideScale = new Scale(shell, SWT.NONE);
    overrideScale.setToolTipText("Scale ToolTip");
    overrideScale.setData("name", "Scale");
    overrideScale.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Slider slider, overrideSlider;
    slider = new Slider(shell, SWT.NONE);
    slider.setToolTipText("Slider ToolTip");

    overrideSlider = new Slider(shell, SWT.NONE);
    overrideSlider.setToolTipText("Slider ToolTip");
    overrideSlider.setData("name", "Slider");
    overrideSlider.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      ProgressBar progressBar, overrideProgressBar;
    if (!SWT.getPlatform().equals("cocoa")) {
        progressBar = new ProgressBar(shell, SWT.NONE);
        progressBar.setSelection(50);
        progressBar.setToolTipText("ProgressBar ToolTip");

        overrideProgressBar = new ProgressBar(shell, SWT.NONE);
        overrideProgressBar.setSelection(50);
        overrideProgressBar.setToolTipText("ProgressBar ToolTip");
        overrideProgressBar.setData("name", "ProgressBar");
        overrideProgressBar.getAccessible().addAccessibleListener(overrideAccessibleAdapter);
    }

    //      Sash sash, overrideSash;
    sash = new Sash(shell, SWT.BORDER);
    sash.setToolTipText("Sash ToolTip");

    overrideSash = new Sash(shell, SWT.BORDER);
    overrideSash.setToolTipText("Sash ToolTip");
    overrideSash.setData("name", "Sash");
    overrideSash.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    //      Link link, overrideLink;
    link = new Link(shell, SWT.NONE);
    link.setText("<a>This is a link</a>");
    link.setToolTipText("Link ToolTip");

    overrideLink = new Link(shell, SWT.NONE);
    overrideLink.setText("<a>This is a link</a>");
    overrideLink.setToolTipText("Link ToolTip");
    overrideLink.setData("name", "Link");
    overrideLink.getAccessible().addAccessibleListener(overrideAccessibleAdapter);

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    largeImage.dispose();
    smallImage.dispose();
    transparentImage.dispose();
    display.dispose();
}

From source file:org.eclipse.swt.examples.paint.PaintExample.java

/**
 * Creates the GUI.//from   w  w w .  j  av a 2s . co m
 */
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() {
        @Override
        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 = 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(widgetSelectedAdapter(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(widgetSelectedAdapter(e -> {
        toolSettings.airbrushIntensity = airbrushIntensityScale.getSelection();
        updateToolSettings();
    }));
}

From source file:SWTImageViewer.java

public void open() {
    shell = new Shell(viewer.shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE);
    shell.setText("Print preview");
    shell.setLayout(new GridLayout(4, false));

    final Button buttonSelectPrinter = new Button(shell, SWT.PUSH);
    buttonSelectPrinter.setText("Select a printer");
    buttonSelectPrinter.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event event) {
            PrintDialog dialog = new PrintDialog(shell);
            // Prompts the printer dialog to let the user select a printer.
            PrinterData printerData = dialog.open();

            if (printerData == null) // the user cancels the dialog
                return;
            // Loads the printer.
            final Printer printer = new Printer(printerData);
            setPrinter(printer, Double.parseDouble(combo.getItem(combo.getSelectionIndex())));
        }//from ww  w. j  a  va  2 s.  c om
    });

    new Label(shell, SWT.NULL).setText("Margin in inches: ");
    combo = new Combo(shell, SWT.READ_ONLY);
    combo.add("0.5");
    combo.add("1.0");
    combo.add("1.5");
    combo.add("2.0");
    combo.add("2.5");
    combo.add("3.0");
    combo.select(1);
    combo.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event event) {
            double value = Double.parseDouble(combo.getItem(combo.getSelectionIndex()));
            setPrinter(printer, value);
        }
    });

    final Button buttonPrint = new Button(shell, SWT.PUSH);
    buttonPrint.setText("Print");
    buttonPrint.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event event) {
            if (printer == null)
                viewer.print();
            else
                viewer.print(printer, margin);
            shell.dispose();
        }
    });

    canvas = new Canvas(shell, SWT.BORDER);
    GridData gridData = new GridData(GridData.FILL_BOTH);
    gridData.horizontalSpan = 4;
    canvas.setLayoutData(gridData);
    canvas.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent e) {
            int canvasBorder = 20;

            if (printer == null || printer.isDisposed())
                return;
            Rectangle rectangle = printer.getBounds();
            Point canvasSize = canvas.getSize();

            double viewScaleFactor = (canvasSize.x - canvasBorder * 2) * 1.0 / rectangle.width;
            viewScaleFactor = Math.min(viewScaleFactor,
                    (canvasSize.y - canvasBorder * 2) * 1.0 / rectangle.height);

            int offsetX = (canvasSize.x - (int) (viewScaleFactor * rectangle.width)) / 2;
            int offsetY = (canvasSize.y - (int) (viewScaleFactor * rectangle.height)) / 2;

            e.gc.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WHITE));
            // draws the page layout
            e.gc.fillRectangle(offsetX, offsetY, (int) (viewScaleFactor * rectangle.width),
                    (int) (viewScaleFactor * rectangle.height));

            // draws the margin.
            e.gc.setLineStyle(SWT.LINE_DASH);
            e.gc.setForeground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));

            int marginOffsetX = offsetX + (int) (viewScaleFactor * margin.left);
            int marginOffsetY = offsetY + (int) (viewScaleFactor * margin.top);
            e.gc.drawRectangle(marginOffsetX, marginOffsetY,
                    (int) (viewScaleFactor * (margin.right - margin.left)),
                    (int) (viewScaleFactor * (margin.bottom - margin.top)));

            if (viewer.image != null) {
                int imageWidth = viewer.image.getBounds().width;
                int imageHeight = viewer.image.getBounds().height;

                double dpiScaleFactorX = printer.getDPI().x * 1.0 / shell.getDisplay().getDPI().x;
                double dpiScaleFactorY = printer.getDPI().y * 1.0 / shell.getDisplay().getDPI().y;

                double imageSizeFactor = Math.min(1,
                        (margin.right - margin.left) * 1.0 / (dpiScaleFactorX * imageWidth));
                imageSizeFactor = Math.min(imageSizeFactor,
                        (margin.bottom - margin.top) * 1.0 / (dpiScaleFactorY * imageHeight));

                e.gc.drawImage(viewer.image, 0, 0, imageWidth, imageHeight, marginOffsetX, marginOffsetY,
                        (int) (dpiScaleFactorX * imageSizeFactor * imageWidth * viewScaleFactor),
                        (int) (dpiScaleFactorY * imageSizeFactor * imageHeight * viewScaleFactor));

            }

        }
    });

    shell.setSize(400, 400);
    shell.open();
    setPrinter(null, 1.0);

    // Set up the event loop.
    while (!shell.isDisposed()) {
        if (!shell.getDisplay().readAndDispatch()) {
            // If no more entries in event queue
            shell.getDisplay().sleep();
        }
    }
}

From source file:PaintExample.java

/**
 * Creates the GUI.//from  w w  w .  ja  v  a 2  s  .  c o m
 */
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();
        }
    });
}

From source file:org.pentaho.di.ui.spoon.trans.TransPerfDelegate.java

public void setupContent() {
    // there is a potential infinite loop below if this method
    // is called when the transgraph is not running, so we check
    // early to make sure it won't happen (see PDI-5009)
    if (!transGraph.isRunning() || transGraph.trans == null
            || !transGraph.trans.getTransMeta().isCapturingStepPerformanceSnapShots()) {
        showEmptyGraph();/* w  w  w  .  j a  v a 2s  .c o m*/
        return; // TODO: display help text and rerty button
    }

    if (perfComposite.isDisposed()) {
        return;
    }

    // Remove anything on the perf composite, like an empty page message
    //
    for (Control control : perfComposite.getChildren()) {
        if (!control.isDisposed()) {
            control.dispose();
        }
    }

    emptyGraph = false;

    this.title = transGraph.trans.getTransMeta().getName();
    this.timeDifference = transGraph.trans.getTransMeta().getStepPerformanceCapturingDelay();
    this.stepPerformanceSnapShots = transGraph.trans.getStepPerformanceSnapShots();

    // Wait a second for the first data to pour in...
    // TODO: make this wait more elegant...
    //
    while (this.stepPerformanceSnapShots == null || stepPerformanceSnapShots.isEmpty()) {
        this.stepPerformanceSnapShots = transGraph.trans.getStepPerformanceSnapShots();
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            // Ignore errors
        }
    }

    Set<String> stepsSet = stepPerformanceSnapShots.keySet();
    steps = stepsSet.toArray(new String[stepsSet.size()]);
    Arrays.sort(steps);

    // Display 2 lists with the data types and the steps on the left side.
    // Then put a canvas with the graph on the right side
    //
    Label dataListLabel = new Label(perfComposite, SWT.NONE);
    dataListLabel.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Metrics.Label"));
    spoon.props.setLook(dataListLabel);
    FormData fdDataListLabel = new FormData();

    fdDataListLabel.left = new FormAttachment(0, 0);
    fdDataListLabel.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdDataListLabel.top = new FormAttachment(0, Const.MARGIN + 5);
    dataListLabel.setLayoutData(fdDataListLabel);

    dataList = new org.eclipse.swt.widgets.List(perfComposite,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    spoon.props.setLook(dataList);
    dataList.setItems(dataChoices);
    dataList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the steps list, we only take the
            // first step in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                stepsList.setSelection(stepsList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });

    FormData fdDataList = new FormData();
    fdDataList.left = new FormAttachment(0, 0);
    fdDataList.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdDataList.top = new FormAttachment(dataListLabel, Const.MARGIN);
    fdDataList.bottom = new FormAttachment(40, Const.MARGIN);
    dataList.setLayoutData(fdDataList);

    Label stepsListLabel = new Label(perfComposite, SWT.NONE);
    stepsListLabel.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Steps.Label"));

    spoon.props.setLook(stepsListLabel);

    FormData fdStepsListLabel = new FormData();
    fdStepsListLabel.left = new FormAttachment(0, 0);
    fdStepsListLabel.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdStepsListLabel.top = new FormAttachment(dataList, Const.MARGIN);
    stepsListLabel.setLayoutData(fdStepsListLabel);

    stepsList = new org.eclipse.swt.widgets.List(perfComposite,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    spoon.props.setLook(stepsList);
    stepsList.setItems(steps);
    stepsList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the data list, we only take the
            // first data item in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                dataList.setSelection(dataList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });
    FormData fdStepsList = new FormData();
    fdStepsList.left = new FormAttachment(0, 0);
    fdStepsList.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdStepsList.top = new FormAttachment(stepsListLabel, Const.MARGIN);
    fdStepsList.bottom = new FormAttachment(100, Const.MARGIN);
    stepsList.setLayoutData(fdStepsList);

    canvas = new Canvas(perfComposite, SWT.NONE);
    spoon.props.setLook(canvas);
    FormData fdCanvas = new FormData();
    fdCanvas.left = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdCanvas.right = new FormAttachment(100, 0);
    fdCanvas.top = new FormAttachment(0, Const.MARGIN);
    fdCanvas.bottom = new FormAttachment(100, 0);
    canvas.setLayoutData(fdCanvas);

    perfComposite.addControlListener(new ControlAdapter() {
        public void controlResized(ControlEvent event) {
            updateGraph();
        }
    });

    perfComposite.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent event) {
            if (image != null) {
                image.dispose();
            }
        }
    });

    canvas.addPaintListener(new PaintListener() {

        public void paintControl(PaintEvent event) {
            if (image != null && !image.isDisposed()) {
                event.gc.drawImage(image, 0, 0);
            }
        }
    });

    // Refresh automatically every 5 seconds as well.
    //
    final Timer timer = new Timer("TransPerfDelegate Timer");
    timer.schedule(new TimerTask() {
        public void run() {
            updateGraph();
        }
    }, 0, 5000);

    // When the tab is closed, we remove the update timer
    //
    transPerfTab.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent arg0) {
            timer.cancel();
        }
    });
}