Example usage for org.eclipse.swt.widgets Display asyncExec

List of usage examples for org.eclipse.swt.widgets Display asyncExec

Introduction

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

Prototype

public void asyncExec(Runnable runnable) 

Source Link

Document

Causes the run() method of the runnable to be invoked by the user-interface thread at the next reasonable opportunity.

Usage

From source file:org.eclipse.swt.snippets.Snippet195.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    Composite comp = new Composite(shell, SWT.NONE);
    comp.setLayout(new FillLayout());
    GLData data = new GLData();
    data.doubleBuffer = true;/*from w  w  w  .  ja v  a2 s.c  om*/
    final GLCanvas canvas = new GLCanvas(comp, SWT.NONE, data);

    canvas.setCurrent();
    GL.createCapabilities();

    canvas.addListener(SWT.Resize, event -> {
        Rectangle bounds = canvas.getBounds();
        float fAspect = (float) bounds.width / (float) bounds.height;
        canvas.setCurrent();
        GL.createCapabilities();
        GL11.glViewport(0, 0, bounds.width, bounds.height);
        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        float near = 0.5f;
        float bottom = -near * (float) Math.tan(45.f / 2);
        float left = fAspect * bottom;
        GL11.glFrustum(left, -left, bottom, -bottom, near, 400.f);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glLoadIdentity();
    });

    GL11.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    GL11.glColor3f(1.0f, 0.0f, 0.0f);
    GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
    GL11.glClearDepth(1.0);
    GL11.glLineWidth(2);
    GL11.glEnable(GL11.GL_DEPTH_TEST);

    shell.setText("SWT/LWJGL Example");
    shell.setSize(640, 480);
    shell.open();

    final Runnable run = new Runnable() {
        int rot = 0;

        @Override
        public void run() {
            if (!canvas.isDisposed()) {
                canvas.setCurrent();
                GL.createCapabilities();
                GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
                GL11.glClearColor(.3f, .5f, .8f, 1.0f);
                GL11.glLoadIdentity();
                GL11.glTranslatef(0.0f, 0.0f, -10.0f);
                float frot = rot;
                GL11.glRotatef(0.15f * rot, 2.0f * frot, 10.0f * frot, 1.0f);
                GL11.glRotatef(0.3f * rot, 3.0f * frot, 1.0f * frot, 1.0f);
                rot++;
                GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);
                GL11.glColor3f(0.9f, 0.9f, 0.9f);
                drawTorus(1, 1.9f + ((float) Math.sin((0.004f * frot))), 15, 15);
                canvas.swapBuffers();
                display.asyncExec(this);
            }
        }
    };
    canvas.addListener(SWT.Paint, event -> run.run());
    display.asyncExec(run);

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

From source file:org.eclipse.swt.snippets.Snippet320.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Snippet 320");
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.SINGLE | SWT.BORDER);
    text.setLayoutData(new GridData(150, SWT.DEFAULT));
    shell.pack();// w  w  w . ja  v  a 2 s . c  o  m
    shell.open();

    final Shell popupShell = new Shell(display, SWT.ON_TOP);
    popupShell.setLayout(new FillLayout());
    final Table table = new Table(popupShell, SWT.SINGLE);
    for (int i = 0; i < 5; i++) {
        new TableItem(table, SWT.NONE);
    }

    text.addListener(SWT.KeyDown, event -> {
        switch (event.keyCode) {
        case SWT.ARROW_DOWN:
            int index = (table.getSelectionIndex() + 1) % table.getItemCount();
            table.setSelection(index);
            event.doit = false;
            break;
        case SWT.ARROW_UP:
            index = table.getSelectionIndex() - 1;
            if (index < 0)
                index = table.getItemCount() - 1;
            table.setSelection(index);
            event.doit = false;
            break;
        case SWT.CR:
            if (popupShell.isVisible() && table.getSelectionIndex() != -1) {
                text.setText(table.getSelection()[0].getText());
                popupShell.setVisible(false);
            }
            break;
        case SWT.ESC:
            popupShell.setVisible(false);
            break;
        }
    });
    text.addListener(SWT.Modify, event -> {
        String string = text.getText();
        if (string.length() == 0) {
            popupShell.setVisible(false);
        } else {
            TableItem[] items = table.getItems();
            for (int i = 0; i < items.length; i++) {
                items[i].setText(string + '-' + i);
            }
            Rectangle textBounds = display.map(shell, null, text.getBounds());
            popupShell.setBounds(textBounds.x, textBounds.y + textBounds.height, textBounds.width, 150);
            popupShell.setVisible(true);
        }
    });

    table.addListener(SWT.DefaultSelection, event -> {
        text.setText(table.getSelection()[0].getText());
        popupShell.setVisible(false);
    });
    table.addListener(SWT.KeyDown, event -> {
        if (event.keyCode == SWT.ESC) {
            popupShell.setVisible(false);
        }
    });

    Listener focusOutListener = event -> display.asyncExec(() -> {
        if (display.isDisposed())
            return;
        Control control = display.getFocusControl();
        if (control == null || (control != text && control != table)) {
            popupShell.setVisible(false);
        }
    });
    table.addListener(SWT.FocusOut, focusOutListener);
    text.addListener(SWT.FocusOut, focusOutListener);

    shell.addListener(SWT.Move, event -> popupShell.setVisible(false));

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

From source file:org.amanzi.splash.chart.Charts.java

private static void displayDataParsingError(final int countBad) {
    final Display display = PlatformUI.getWorkbench().getDisplay();
    display.asyncExec(new Runnable() {

        @Override/*  w w w . j a  va2s  .com*/
        public void run() {
            ErrorDialog.openError(display.getActiveShell(), "Invalid input",
                    "There were " + countBad + " data parsing errors in creating the chart!",
                    new Status(Status.ERROR, SplashPlugin.getId(), NumberFormatException.class.getName()));
        }

    });
}

From source file:org.amanzi.splash.chart.Charts.java

/**
 * @param e//from   ww  w.j a  v  a  2 s.  co m
 */
private static void showErrorDlg(final NumberFormatException e) {
    final Display display = PlatformUI.getWorkbench().getDisplay();
    display.asyncExec(new Runnable() {

        @Override
        public void run() {
            ErrorDialog.openError(display.getActiveShell(), "Invalid input",
                    "Chart can't be created due to invalid input!",
                    new Status(Status.ERROR, SplashPlugin.getId(), NumberFormatException.class.getName(), e));
        }

    });
}

From source file:org.eclipse.swt.examples.javaviewer.JavaViewer.java

void open(String name) {
    final String textString;

    if ((name == null) || (name.length() == 0))
        return;/*w  w w  .  ja va 2s  . com*/

    File file = new File(name);
    if (!file.exists()) {
        String message = MessageFormat.format(resources.getString("Err_file_no_exist"), file.getName());
        displayError(message);
        return;
    }

    try {
        FileInputStream stream = new FileInputStream(file.getPath());
        try (Reader in = new BufferedReader(new InputStreamReader(stream))) {

            char[] readBuffer = new char[2048];
            StringBuilder buffer = new StringBuilder((int) file.length());
            int n;
            while ((n = in.read(readBuffer)) > 0) {
                buffer.append(readBuffer, 0, n);
            }
            textString = buffer.toString();
            stream.close();
        } catch (IOException e) {
            // Err_file_io
            String message = MessageFormat.format(resources.getString("Err_file_io"), file.getName());
            displayError(message);
            return;
        }
    } catch (FileNotFoundException e) {
        String message = MessageFormat.format(resources.getString("Err_not_found"), file.getName());
        displayError(message);
        return;
    }
    // Guard against superfluous mouse move events -- defer action until later
    Display display = text.getDisplay();
    display.asyncExec(() -> text.setText(textString));

    // parse the block comments up front since block comments can go across
    // lines - inefficient way of doing this
    lineStyler.parseBlockComments(textString);
}

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) {// w w w  . j  a  v a 2s  .  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) {// w  w  w.  jav a2  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:JavaViewer.java

void open(String name) {
    final String textString;

    if ((name == null) || (name.length() == 0))
        return;//  w w w .java  2  s .com

    File file = new File(name);
    if (!file.exists()) {
        String message = "Err file no exist";
        displayError(message);
        return;
    }

    try {
        FileInputStream stream = new FileInputStream(file.getPath());
        try {
            Reader in = new BufferedReader(new InputStreamReader(stream));
            char[] readBuffer = new char[2048];
            StringBuffer buffer = new StringBuffer((int) file.length());
            int n;
            while ((n = in.read(readBuffer)) > 0) {
                buffer.append(readBuffer, 0, n);
            }
            textString = buffer.toString();
            stream.close();
        } catch (IOException e) {
            // Err_file_io
            String message = "Err_file_io";
            displayError(message);
            return;
        }
    } catch (FileNotFoundException e) {
        String message = "Err_not_found";
        displayError(message);
        return;
    }
    // Guard against superfluous mouse move events -- defer action until
    // later
    Display display = text.getDisplay();
    display.asyncExec(new Runnable() {
        public void run() {
            text.setText(textString);
        }
    });

    // parse the block comments up front since block comments can go across
    // lines - inefficient way of doing this
    lineStyler.parseBlockComments(textString);
}

From source file:org.gumtree.vis.swt.PlotComposite.java

public void handleException(final Exception e) {
    Display display = Display.getCurrent();
    if (display == null) {
        display = Display.getDefault();/*from  w w  w  . j av a 2s.  co m*/
    }
    display.asyncExec(new Runnable() {
        @Override
        public void run() {
            if (getShell() != null) {
                MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.OK);
                messageBox.setText("Failed to Save");
                messageBox.setMessage("failed : " + e.getMessage());
                messageBox.open();
                //               MessageDialog.openError(getShell(), "Failed to Save", "failed to save " +
                //                     "the image: " + e.getMessage());

            }
        }
    });
}

From source file:org.gumtree.vis.swt.PlotComposite.java

public void setPlot(final IPlot plot) {
    final IPlot oldPlot = this.plot;
    if (oldPlot != null) {
        oldPlot.cleanUp();//  w  w  w . ja  va2  s .  c  o m
        frame.remove((JPanel) oldPlot);
    }
    this.plot = plot;
    final Composite composite = this;
    Display display = Display.getCurrent();
    if (display == null) {
        display = Display.getDefault();
    }
    display.asyncExec(new Runnable() {

        @Override
        public void run() {
            if (!composite.isDisposed()) {
                embedPlot(plot);
                removeListeners(oldPlot);
                addListeners();
                composite.pack();
                composite.getParent().layout(true, true);
            }
        }
    });
}