Example usage for javax.swing SwingUtilities invokeAndWait

List of usage examples for javax.swing SwingUtilities invokeAndWait

Introduction

In this page you can find the example usage for javax.swing SwingUtilities invokeAndWait.

Prototype

public static void invokeAndWait(final Runnable doRun) throws InterruptedException, InvocationTargetException 

Source Link

Document

Causes doRun.run() to be executed synchronously on the AWT event dispatching thread.

Usage

From source file:org.eurocarbdb.application.glycoworkbench.plugin.s3.Cockpit.java

/**
 * Lists the buckets in the user's S3 account and refreshes the GUI to display
 * these buckets. Any buckets or objects already listed in the GUI are cleared first.
 *///from w  w  w.  j  a v  a 2s  .  c o  m
private void listAllBuckets() {
    // Remove current bucket and object data from models.
    cachedBuckets.clear();
    bucketsTable.clearSelection();
    bucketTableModel.removeAllBuckets();
    objectTableModel.removeAllObjects();
    final Cockpit myself = this;

    // This is all very convoluted. This was necessary so we can display the status dialog box.
    runInBackgroundThread(new Runnable() {
        public void run() {
            if (!cloudFrontMembershipChecked) {
                // Check whether the user is signed-up for CloudFront.
                startProgressDialog("Checking for CloudFront account membership");
                try {
                    cloudFrontService = new CloudFrontService(s3ServiceMulti.getAWSCredentials(),
                            APPLICATION_DESCRIPTION, myself, null, null);
                    cloudFrontService.listDistributions();
                } catch (CloudFrontServiceException e) {
                    stopProgressDialog();

                    if ("OptInRequired".equals(e.getErrorCode())) {
                        log.debug("Your AWS account is not subscribed to the Amazon CloudFront service, "
                                + "you will not be able to manage distributions");
                    }
                    cloudFrontService = null;
                } finally {
                    stopProgressDialog();

                    try {
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                cloudFrontMembershipChecked = true;

                                // Update the bucket table to show, or not show, distributions
                                bucketTableModel = new BucketTableModel(cloudFrontService != null);
                                bucketTableModelSorter = new TableSorter(bucketTableModel);
                                bucketsTable.setModel(bucketTableModelSorter);
                                bucketTableModelSorter.setTableHeader(bucketsTable.getTableHeader());

                                if (cloudFrontService != null) {
                                    // Set column width for Cloud Front distributions indicator.
                                    TableColumn distributionFlagColumn = bucketsTable.getColumnModel()
                                            .getColumn(1);
                                    int distributionFlagColumnWidth = 18;
                                    distributionFlagColumn.setPreferredWidth(distributionFlagColumnWidth);
                                    distributionFlagColumn.setMaxWidth(distributionFlagColumnWidth);
                                    distributionFlagColumn.setMinWidth(0);
                                }

                                manageDistributionsMenuItem.setEnabled(cloudFrontService != null);

                            }
                        });
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            startProgressDialog("Listing buckets for " + s3ServiceMulti.getAWSCredentials().getAccessKey());
            try {
                final S3Bucket[] buckets = s3ServiceMulti.getS3Service().listAllBuckets();

                // Lookup user's CloudFront distributions.
                Distribution[] distributions = new Distribution[] {};
                if (cloudFrontService != null) {
                    updateProgressDialog(
                            "Listing distributions for " + cloudFrontService.getAWSCredentials().getAccessKey(),
                            "", 0);
                    distributions = cloudFrontService.listDistributions();
                }
                final Distribution[] finalDistributions = distributions;

                runInDispatcherThreadImmediately(new Runnable() {
                    public void run() {
                        for (int i = 0; i < buckets.length; i++) {
                            // Determine whether each bucket has one or more CloudFront distributions.
                            boolean bucketHasDistribution = false;
                            for (int j = 0; j < finalDistributions.length; j++) {
                                if (finalDistributions[j].getOrigin()
                                        .equals(buckets[i].getName() + ".s3.amazonaws.com")) {
                                    bucketHasDistribution = true;
                                }
                            }

                            bucketTableModel.addBucket(buckets[i], bucketHasDistribution);

                            if (i == 0) {
                                ownerFrame.setTitle(
                                        APPLICATION_TITLE + " : " + buckets[i].getOwner().getDisplayName());
                            }
                        }
                    }
                });
            } catch (final Exception e) {
                stopProgressDialog();

                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        logoutEvent();

                        String message = "Unable to list your buckets in S3, please log in again";
                        log.error(message, e);
                        ErrorDialog.showDialog(ownerFrame, null, message, e);

                        loginEvent(null);
                    }
                });
            } finally {
                stopProgressDialog();
            }
        };
    });
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.s3.gui.StartupDialog.java

private void retrieveCredentialsFromS3(String passphrase, final String password) {
    if (!validPassphraseInputs(passphrase, password)) {
        return;/*  w w  w.j  a  v a  2 s  .c o m*/
    }

    final String[] bucketName = new String[1];
    final String[] credentialObjectKey = new String[1];

    try {
        bucketName[0] = generateBucketNameFromPassphrase(passphrase);
        credentialObjectKey[0] = generateObjectKeyFromPassphrase(passphrase, password);
    } catch (Exception e) {
        String message = "Unable to generate bucket name or object key";
        log.error(message, e);
        ErrorDialog.showDialog(this, hyperlinkListener, message, e);
        return;
    }

    final ProgressDialog progressDialog = new ProgressDialog(ownerFrame, "Retrieving AWS Credentials", null);
    final StartupDialog myself = this;

    (new Thread(new Runnable() {
        public void run() {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    progressDialog.startDialog("Downloading your AWS Credentials", "", 0, 0, null, null);
                }
            });

            S3Object encryptedCredentialsObject = null;

            try {
                S3Service s3Service = new RestS3Service(null);
                encryptedCredentialsObject = s3Service.getObject(new S3Bucket(bucketName[0]),
                        credentialObjectKey[0]);
            } catch (S3ServiceException e) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        progressDialog.stopDialog();
                    }
                });

                final String errorMessage = "<html><center>Unable to find your AWS Credentials in S3"
                        + "<br><br>Please check your passphrase and password</center></html>";
                log.error(errorMessage, e);
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                            ErrorDialog.showDialog(myself, hyperlinkListener, errorMessage, null);
                        }
                    });
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (InvocationTargetException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                return;
            }

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    progressDialog.updateDialog("Decrypting your AWS Credentials", null, 0);
                }
            });

            try {
                myself.awsCredentials = AWSCredentials.load(password,
                        new BufferedInputStream(encryptedCredentialsObject.getDataInputStream()));

                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        progressDialog.stopDialog();
                    }
                });
                myself.setVisible(false);
            } catch (S3ServiceException e) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        progressDialog.stopDialog();
                    }
                });

                String errorMessage = "<html><center>Unable to load your AWS Credentials from S3: "
                        + "<br><br>Please check your password</center></html>";
                log.error(errorMessage, e);
                ErrorDialog.showDialog(myself, hyperlinkListener, errorMessage, null);
            }

        }
    })).start();
}

From source file:org.gephi.desktop.importer.DesktopImportControllerUI.java

private void finishImport(Container container) {
    if (container.verify()) {
        Report report = container.getReport();

        //Report panel
        ReportPanel reportPanel = new ReportPanel();
        reportPanel.setData(report, container);
        DialogDescriptor dd = new DialogDescriptor(reportPanel,
                NbBundle.getMessage(DesktopImportControllerUI.class, "ReportPanel.title"));
        if (!DialogDisplayer.getDefault().notify(dd).equals(NotifyDescriptor.OK_OPTION)) {
            reportPanel.destroy();//  w w  w . j a v a2 s.  c om
            return;
        }
        reportPanel.destroy();
        final Processor processor = reportPanel.getProcessor();

        //Project
        Workspace workspace = null;
        ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
        ProjectControllerUI pcui = Lookup.getDefault().lookup(ProjectControllerUI.class);
        if (pc.getCurrentProject() == null) {
            pcui.newProject();
            workspace = pc.getCurrentWorkspace();
        }

        //Process
        final ProcessorUI pui = getProcessorUI(processor);
        final ValidResult validResult = new ValidResult();
        if (pui != null) {
            if (pui != null) {
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            String title = NbBundle.getMessage(DesktopImportControllerUI.class,
                                    "DesktopImportControllerUI.processor.ui.dialog.title");
                            JPanel panel = pui.getPanel();
                            pui.setup(processor);
                            final DialogDescriptor dd2 = new DialogDescriptor(panel, title);
                            if (panel instanceof ValidationPanel) {
                                ValidationPanel vp = (ValidationPanel) panel;
                                vp.addChangeListener(new ChangeListener() {
                                    @Override
                                    public void stateChanged(ChangeEvent e) {
                                        dd2.setValid(!((ValidationPanel) e.getSource()).isProblem());
                                    }
                                });
                                dd2.setValid(!vp.isProblem());
                            }
                            Object result = DialogDisplayer.getDefault().notify(dd2);
                            if (result.equals(NotifyDescriptor.CANCEL_OPTION)
                                    || result.equals(NotifyDescriptor.CLOSED_OPTION)) {
                                validResult.setResult(false);
                            } else {
                                pui.unsetup(); //true
                                validResult.setResult(true);
                            }
                        }
                    });
                } catch (InterruptedException ex) {
                    Exceptions.printStackTrace(ex);
                } catch (InvocationTargetException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
        if (validResult.isResult()) {
            controller.process(container, processor, workspace);

            //StatusLine notify
            String source = container.getSource();
            if (source.isEmpty()) {
                source = NbBundle.getMessage(DesktopImportControllerUI.class,
                        "DesktopImportControllerUI.status.importSuccess.default");
            }
            StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(DesktopImportControllerUI.class,
                    "DesktopImportControllerUI.status.importSuccess", source));
        }
    } else {
        System.err.println("Bad container");
    }
}

From source file:org.jab.docsearch.DocSearch.java

/**
 * Question dialog for yes or no that returns true for yes and false for no
 *
 * @return true for yes and false for no
 *///w ww . j  a  va 2s  .  c  o  m
@SuppressWarnings("unused")
private boolean getConfirmationMessage(String title, String details) {
    MessageConfirmRunner mct = new MessageConfirmRunner(title, details, this);

    try {
        SwingUtilities.invokeAndWait(mct);

        if (mct.getReturnInt() == JOptionPane.YES_OPTION) {
            return true;
        }
    } catch (InterruptedException ie) {
        logger.fatal("getConfirmationMessage() failed with InterruptedException", ie);
    } catch (InvocationTargetException ite) {
        logger.fatal("getConfirmationMessage() failed with InvocationTargetException", ite);
    }

    return false;
}

From source file:org.jactr.modules.pm.motor.MotorModuleTest.java

protected JFrame openWindow() {
    final JFrame frame = new JFrame("TextInput");

    try {/*from w  w w  .jav  a2 s  . c o m*/
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                JTextArea textArea = new JTextArea();
                frame.getContentPane().add(new JScrollPane(textArea));
                frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
                frame.setVisible(true);
                textArea.grabFocus();
            }
        });
    } catch (Exception e) {

    }

    return frame;
}

From source file:org.jajuk.base.Device.java

/**
 * Prepare manual refresh.//from   w w w.ja v  a  2  s. c o  m
 * 
 * @param bAsk ask user to perform deep or fast refresh 
 * 
 * @return the user choice (deep or fast)
 * 
 * @throws JajukException if user canceled, device cannot be refreshed or device already
 * refreshing
 */
int prepareRefresh(final boolean bAsk) throws JajukException {
    if (bAsk) {
        final Object[] possibleValues = { Messages.getString("FilesTreeView.60"), // fast
                Messages.getString("FilesTreeView.61"), // deep
                Messages.getString("Cancel") };// cancel
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    choice = JOptionPane.showOptionDialog(JajukMainWindow.getInstance(),
                            Messages.getString("FilesTreeView.59"), Messages.getString("Option"),
                            JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, possibleValues,
                            possibleValues[0]);
                }
            });
        } catch (Exception e) {
            Log.error(e);
            choice = Device.OPTION_REFRESH_CANCEL;
        }
        if (choice == Device.OPTION_REFRESH_CANCEL) { // Cancel
            return choice;
        }
    }
    // JajukException are not trapped, will be thrown to the caller
    final Device device = this;
    if (!device.isMounted()) {
        // Leave if user canceled device mounting
        if (!device.mount(true)) {
            return Device.OPTION_REFRESH_CANCEL;
        }
    }
    if (bAlreadyRefreshing) {
        throw new JajukException(107);
    }
    return choice;
}

From source file:org.languagetool.gui.LanguageToolSupport.java

private synchronized List<RuleMatch> checkText(Object caller) throws IOException {
    if (this.mustDetectLanguage) {
        mustDetectLanguage = false;/*from  w w w . jav a 2 s. co  m*/
        if (!this.textComponent.getText().isEmpty()) {
            Language detectedLanguage = autoDetectLanguage(this.textComponent.getText());
            if (!detectedLanguage.equals(this.languageTool.getLanguage())) {
                reloadLanguageTool(detectedLanguage);
                if (SwingUtilities.isEventDispatchThread()) {
                    fireEvent(LanguageToolEvent.Type.LANGUAGE_CHANGED, caller);
                } else {
                    try {
                        SwingUtilities.invokeAndWait(
                                () -> fireEvent(LanguageToolEvent.Type.LANGUAGE_CHANGED, caller));
                    } catch (InterruptedException ex) {
                        //ignore
                    } catch (InvocationTargetException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    }
    if (SwingUtilities.isEventDispatchThread()) {
        fireEvent(LanguageToolEvent.Type.CHECKING_STARTED, caller);
    } else {
        try {
            SwingUtilities.invokeAndWait(() -> fireEvent(LanguageToolEvent.Type.CHECKING_STARTED, caller));
        } catch (InterruptedException ex) {
            //ignore
        } catch (InvocationTargetException ex) {
            throw new RuntimeException(ex);
        }
    }

    long startTime = System.currentTimeMillis();
    List<RuleMatch> matches = this.languageTool.check(this.textComponent.getText());
    long elapsedTime = System.currentTimeMillis() - startTime;

    int v = check.get();
    if (v == 0) {
        if (!SwingUtilities.isEventDispatchThread()) {
            SwingUtilities.invokeLater(() -> {
                updateHighlights(matches);
                fireEvent(LanguageToolEvent.Type.CHECKING_FINISHED, caller, elapsedTime);
            });
        } else {
            updateHighlights(matches);
            fireEvent(LanguageToolEvent.Type.CHECKING_FINISHED, caller, elapsedTime);
        }
    }
    return matches;
}

From source file:org.notebook.gui.widget.LookAndFeelSelector.java

/**
 * Sets the look and feel.//from   w w  w  .  j av  a  2  s.c  o  m
 * 
 * @param theme
 *            the new look and feel
 */
public void setLookAndFeel(String theme) {
    try {
        log.info("Updating skin '" + theme + "'");
        if (skins.containsKey(theme)) {
            UIManager.setLookAndFeel(skins.get(theme));
        } else {
            log.error("Not found skin '" + theme + "'");
            return;
        }

        /** fix font bug start */
        if (SwingUtilities.isEventDispatchThread()) {
            fixFontBug();
        } else {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    fixFontBug();
                }
            });
        }
    } catch (Exception e) {
        log.error(e.toString(), e);
    }

    /**
     * ??????
     * tiptool
     */
    if (!isDefaultLookAndFeel(theme)) {
        // Get border color
        try {
            Color c = SubstanceLookAndFeel.getCurrentSkin().getMainActiveColorScheme().getMidColor();
            UIManager.put("ToolTip.border", BorderFactory.createLineBorder(c));
            UIManager.put("ToolTip.background", new ColorUIResource(Color.WHITE));
            UIManager.put("ToolTip.foreground", new ColorUIResource(Color.BLACK));

            SubstanceSkin skin = SubstanceLookAndFeel.getCurrentSkin();
            SubstanceColorScheme scheme = skin.getMainActiveColorScheme();

            GuiUtils.putLookAndFeelColor("borderColor", scheme.getMidColor());
            GuiUtils.putLookAndFeelColor("lightColor", scheme.getLightColor());
            GuiUtils.putLookAndFeelColor("lightBackgroundFillColor", scheme.getLightBackgroundFillColor());
            GuiUtils.putLookAndFeelColor("darkColor", scheme.getDarkColor());
            GuiUtils.putLookAndFeelColor("backgroundFillColor", scheme.getBackgroundFillColor());
            GuiUtils.putLookAndFeelColor("lineColor", scheme.getLineColor());
            GuiUtils.putLookAndFeelColor("selectionForegroundColor", scheme.getSelectionForegroundColor());
            GuiUtils.putLookAndFeelColor("selectionBackgroundColor", scheme.getSelectionBackgroundColor());
            GuiUtils.putLookAndFeelColor("foregroundColor", scheme.getForegroundColor());
            GuiUtils.putLookAndFeelColor("focusRingColor", scheme.getFocusRingColor());

        } catch (Exception e) {
            log.info("This is not a SubstanceLookAndFeel skin.");
        }

        UIManager.put(LafWidget.ANIMATION_KIND, LafConstants.AnimationKind.NONE);
        UIManager.put(SubstanceLookAndFeel.TABBED_PANE_CONTENT_BORDER_KIND,
                SubstanceConstants.TabContentPaneBorderKind.SINGLE_FULL);

        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
    }
}

From source file:org.omegat.gui.scripting.ScriptRunner.java

private static void invokeGuiScript(Invocable engine) throws ScriptException {
    Runnable invoke = () -> {// ww w  . j  a  v a2  s .c  o m
        try {
            engine.invokeFunction(SCRIPT_GUI_FUNCTION_NAME);
        } catch (NoSuchMethodException e) {
            // No GUI invocation defined
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
    };
    if (SwingUtilities.isEventDispatchThread()) {
        invoke.run();
    } else {
        try {
            SwingUtilities.invokeAndWait(invoke);
        } catch (InvocationTargetException e) {
            // The original cause is double-wrapped at this point
            if (e.getCause().getCause() instanceof ScriptException) {
                throw (ScriptException) e.getCause().getCause();
            } else {
                Log.log(e);
            }
        } catch (InterruptedException e) {
            Log.log(e);
        }
    }
}

From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java

/**
 * Setting up the data fields and retrieving parameters from the applet attributes.
 * // w  w w  . j a  v a 2  s . c  o  m
 */
public void init() {

    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {

                smcsa = new SmartCardSignerPanel();

                createGUI();
                strRelURL = getParameter("relURL");

                strCookieName = getParameter("cookieName");
                strCookieValue = getParameter("cookieValue");
                strCookie = strCookieName + "=" + strCookieValue;

                userName = getParameter("name");
                userForename = getParameter("forename");
                userEmailaddress = getParameter("emailaddress");

                String strPrivileges = getParameter("privileges");

                privInt = Integer.parseInt(strPrivileges);

                if (privInt >= 1) {

                    privilegedServlet = "Privileged";

                }

                mode = getParameter("mode");
                endparticipation = getParameter("endparticipation");

                //If intended use is to sign a standard-consent
                if (mode.equalsIgnoreCase("signonly")) {

                    requestStandardConsentDocument(!Boolean.parseBoolean(endparticipation));

                    smcsa.setDocument(cda, new StoreSignedConsentListener());

                    remove(scp);

                    setContentPane(smcsa);

                    validate();

                } else {
                    requestData();
                    setData();
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("createGUI didn't successfully complete");
    }
}