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:edu.mit.fss.examples.visual.gui.WorldWindVisualization.java

@Override
public void objectRemoved(ObjectChangeEvent event) {
    if (event.getObject() instanceof Element) {
        final Element element = (Element) event.getObject();

        try {//www .  ja va2 s.  c  o  m
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    if (element instanceof OrbitalElement) {
                        OrbitalElement orbital = (OrbitalElement) element;
                        // remove orbital shape from display layer
                        displayLayer.removeRenderable(optionsPanel.getOrbitalShape(orbital));
                        // remove footprint shape from display layer
                        displayLayer.removeRenderable(optionsPanel.getFootprintShape(orbital));
                        optionsPanel.removeElement(orbital);
                    } else if (element instanceof SurfaceElement) {
                        optionsPanel.removeElement((SurfaceElement) element);
                        // update markers layer (cannot remove individual markers)
                        markerLayer.setMarkers(optionsPanel.getSurfaceMarkers());
                    }
                }
            });
        } catch (InvocationTargetException | InterruptedException e) {
            logger.error(e);
        }
    }
}

From source file:biomine.bmvis2.Vis.java

/**
 * Common initialization method called by Applet's overridden init() and
 * our private CLI init(String[] args).//from  w  w  w .j  ava  2  s. c o  m
 */
private void initWindow() {
    try {
        // Set cross-platform Java L&F (also called "Metal")

        // UIManager.setLookAndFeel(
        //         UIManager.getCrossPlatformLookAndFeelClassName());

        // System default
        // UIManager.setLookAndFeel(
        //        UIManager.getSystemLookAndFeelClassName());
        String os = System.getProperty("os.name");
        if (os.startsWith("Mac OS")) {
            // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            // UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        } else if (os.startsWith("Windows")) {
            // UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } else {
            Logging.info("ui", "Unknown operating system: " + os + ", not setting a specific Look&Feel.");
        }
        // MOTIF!
        // UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
    } catch (Exception e) {
        // handle exception
    }

    String[] logCategories = { "enduser", "graph_reading", "expand", "js" };
    Logging.init(Arrays.asList(logCategories), Logging.LEVEL_DEBUG);
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                Vis.this.createGUI("BMVIS II");
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        Logging.error("ui", "Failed to create GUI!");
        System.exit(1);
    }

    this.addFocusListener(focusListener);
}

From source file:net.sf.dsig.DSApplet.java

/**
 * Sign a form using the certificate with the supplied alias
 * @param formId the id of the form to lookup through DOM traversal
 * @param alias the alias of the selected certificate
 * @return true if signing has completed successfully, false otherwise
 * @category JavaScript exposed method/*from w ww .j  a v a 2  s  .  c  o m*/
 * @since 2.1.0
 */
public boolean sign(final String formId, final String alias) {
    class SignInternalRunnable implements Runnable {
        private boolean successful;

        public boolean isSuccessful() {
            return successful;
        }

        @Override
        public void run() {
            successful = signInternal(formId, alias);
        }
    }
    SignInternalRunnable sir = new SignInternalRunnable();

    available.acquireUninterruptibly();
    try {
        if (alias != null) {
            return signInternal(formId, alias);
        }

        // Null alias means the certificate selection dialog box will pop-up; 
        // hence, we need to be running in Swing's event dispatch thread
        if (!SwingUtilities.isEventDispatchThread()) {
            SwingUtilities.invokeAndWait(sir);
        } else {
            sir.run();
        }

        return sir.isSuccessful();
    } catch (Exception e) {
        logger.error("Internal sign failed", e);

        return false;
    } finally {
        available.release();
    }
}

From source file:com.sshtools.j2ssh.authentication.UserGridCredential.java

private static void errorReport(final java.awt.Component comp, final String message, final Exception ex) {
    try {//from  w  w w .j  a  v a  2 s  .  com
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                SshToolsApplicationPanel.showErrorMessage(comp, message, "GSI-SSHTerm Authentication", ex);
            }
        });
    } catch (Exception ex1) {
        log.info("Failed to invoke message box through SwingUtilities", ex1);
    }
}

From source file:net.sf.dsig.DSApplet.java

/**
 * Sign the supplied plaintext using the certificate with the supplied alias
 * @param plaintext the plaintext to sign
 * @param alias the alias of the selected certificate
 * @return a jsonResponse containing the signature
 * @since 2.2.0// ww  w  . j  a v a2 s.  c om
 * @category JavaScript exposed method
 */
public String signPlaintext(final String plaintext, final String alias) {
    class SignPlaintextInternalRunnable implements Runnable {
        private String jsonResponse;

        public String getJsonResponse() {
            return jsonResponse;
        }

        @Override
        public void run() {
            jsonResponse = signPlaintextInternal(plaintext, alias);
        }
    }
    SignPlaintextInternalRunnable spir = new SignPlaintextInternalRunnable();

    available.acquireUninterruptibly();
    try {
        if (alias != null) {
            return signPlaintextInternal(plaintext, alias);
        }

        // Null alias means the certificate selection dialog box will pop-up; 
        // hence, we need to be running in Swing's event dispatch thread
        if (!SwingUtilities.isEventDispatchThread()) {
            SwingUtilities.invokeAndWait(spir);
        } else {
            spir.run();
        }

        return spir.getJsonResponse();
    } catch (Exception e) {
        logger.error("Internal sign plaintext failed", e);

        return "";
    } finally {
        available.release();
    }
}

From source file:net.sf.jhylafax.JHylaFAX.java

private String requestPassword(final ProgressMonitor monitor, final boolean admin)
        throws ServerResponseException {
    final String[] password = new String[1];
    Runnable runner = new Runnable() {
        public void run() {
            String host = Settings.USERNAME.getValue() + "@" + Settings.HOSTNAME.getValue();
            password[0] = Dialogs.requestPassword(monitor.getComponent(),
                    (admin) ? i18n.tr("Enter admin password for {0}:", host)
                            : i18n.tr("Enter password for {0}:", host),
                    i18n.tr("JHylaFAX Connection"));
        }/*from w  w w  . j  a  va2 s.  co m*/
    };
    try {
        SwingUtilities.invokeAndWait(runner);
        return password[0];
    } catch (InterruptedException e) {
        logger.error("Unexpected exception while waiting for password", e);
        throw new ServerResponseException(i18n.tr("Abort by user."));
    } catch (InvocationTargetException e) {
        logger.error("Unexpected exception while waiting for password", e);
        throw new ServerResponseException(i18n.tr("Abort by user."));
    }
}

From source file:org.martus.client.swingui.FxInSwingMainWindow.java

public void runInUiThreadAndWait(Runnable toRun) throws InterruptedException, InvocationTargetException {
    if (SwingUtilities.isEventDispatchThread()) {
        toRun.run();/*w w  w  . j a va2  s .  co  m*/
        return;
    }

    SwingUtilities.invokeAndWait(toRun);
}

From source file:com.jaspersoft.ireport.designer.data.fieldsproviders.BeanInspectorPanel.java

/**
 * Set the columns error message in the ReportQueryDialog....
 * This is called from a none swing thread, hence all the invoke and
 * wait magic.//  w w  w . j ava 2s.com
 * The message is only set if the query string matches the one the 
 * error message is for.
 *
 * @param columns The list of columns to set.
 */
protected void setColumnErrorFromWork(final String error_msg) {
    try {

        Runnable r = new Runnable() {
            public void run() {
                getReportQueryDialog().setColumnsError(error_msg);
                getReportQueryDialog().getQueryEditorPane().requestFocusInWindow();
            }
        };

        if (SwingUtilities.isEventDispatchThread()) {
            r.run();
        } else {
            SwingUtilities.invokeAndWait(r);
        }

    } catch (Exception e) {
        // oh well we got interrupted.
    }
}

From source file:com.sshtools.common.ui.SshToolsApplicationClientPanel.java

/**
 *
 *
 * @param newProfile//from  ww  w .ja  v  a 2s.c o  m
 *
 * @return
 *
 * @throws IOException
 */
protected boolean authenticateUser(boolean newProfile) throws IOException {
    try {
        // We should now authenticate
        int result = AuthenticationProtocolState.READY;

        // Our authenticated flag
        boolean authenticated = false;

        // Get the supported authentication methods
        java.util.List auths = SshAuthenticationClientFactory.getSupportedMethods();

        // Get the available methods
        java.util.List supported = null;
        supported = ssh.getAvailableAuthMethods(getCurrentConnectionProfile().getUsername());

        if (supported == null)
            throw new IOException(
                    "There are no authentication methods which both the server and client understand.\n Cannot connect.");

        // If the server supports external key exchange then we SHOULD use it 
        if (supported.contains("external-keyx")) {

            EKEYXAuthenticationClient aa = new EKEYXAuthenticationClient();
            aa.setProperties(getCurrentConnectionProfile());
            aa.setUsername(getCurrentConnectionProfile().getUsername());
            result = ssh.authenticate(aa, getCurrentConnectionProfile().getHost());

            if (result == AuthenticationProtocolState.COMPLETE) {
                authenticationComplete(newProfile);
                return true;
            }
        }
        // If the server supports public key lets look for an agent and try
        // some of his keys
        if (supported.contains("publickey")) {
            if (System.getProperty("sshtools.agent") != null) {
                try {
                    SshAgentClient agent = SshAgentClient.connectLocalAgent("SSHTerm",
                            System.getProperty("sshtools.agent") /*, 5*/);

                    AgentAuthenticationClient aac = new AgentAuthenticationClient();
                    aac.setAgent(agent);
                    aac.setUsername(getCurrentConnectionProfile().getUsername());
                    result = ssh.authenticate(aac, getCurrentConnectionProfile().getHost());

                    agent.close();
                } catch (AgentNotAvailableException ex) {
                    log.info("No agent was available for authentication");

                    // Just continue
                }

                if (result == AuthenticationProtocolState.COMPLETE) {
                    authenticationComplete(newProfile);

                    return true;
                }
            }
        }

        // Create a list for display that will contain only the
        // supported and available methods
        java.util.List display = new java.util.ArrayList();

        // Did we receive a banner from the remote computer
        final String banner = ssh.getAuthenticationBanner(BANNER_TIMEOUT);

        if (banner != null) {
            if (!banner.trim().equals("")) {
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                            BannerDialog.showBannerDialog(SshToolsApplicationClientPanel.this, banner);
                        }
                    });
                } catch (Exception e) {
                    log.error("Failed to invoke and wait on BannerDialog", e);
                }
            }
        }

        // Are there any authentication methods within the properties file?
        // Iterate through selecting only the supported and available
        Iterator it = supported.iterator();

        LinkedList allowed = new LinkedList();

        while (it.hasNext() && !authenticated) {
            Object obj = it.next();

            if (auths.contains(obj)) {
                display.add(obj);
                allowed.add(obj);
                //System.out.println(obj);
            }
        }

        // First look to see if we have any authenticaiton methods available
        // in the profile properties object as this will overide a manual selection
        java.util.Map authMethods = (Map) ((HashMap) getCurrentConnectionProfile().getAuthenticationMethods())
                .clone();
        it = authMethods.entrySet().iterator();

        //Iterator it2 = null;
        java.util.List selected;

        // Loop until the user either cancels or completes
        boolean completed = false;
        SshAuthenticationClient auth;
        Map.Entry entry;
        String msg = null;

        while (!completed && (ssh.getConnectionState().getValue() != TransportProtocolState.DISCONNECTED)) {
            auth = null;
            // Select an authentication method from the properties file or
            // prompt the user to choose
            if (it.hasNext()) {
                Object obj = it.next();

                if (obj instanceof Map.Entry) {
                    entry = (Map.Entry) obj;
                    auth = (SshAuthenticationClient) entry.getValue();
                } else if (obj instanceof String) {
                    auth = SshAuthenticationClientFactory.newInstance((String) obj,
                            getCurrentConnectionProfile());
                    auth.setUsername(getCurrentConnectionProfile().getUsername());
                } else {
                    closeConnection(true);
                    throw new IOException("Iterator of Map or List of String expected");
                }
            } else {
                selected = AuthenticationDialog.showAuthenticationDialog(this, display,
                        ((msg == null) ? "" : msg));

                if (selected.size() > 0) {
                    it = selected.iterator();
                } else {
                    closeConnection(true);

                    return false;
                }
            }
            if (auth != null && !allowed.contains(auth.getMethodName()))
                auth = null;
            if (auth != null) {
                // The password authentication client can act upon requests to change the password

                /* if (auth instanceof PasswordAuthenticationClient) {
                   PasswordAuthenticationDialog dialog = new PasswordAuthenticationDialog(SshTerminalPanel.this);
                   ((PasswordAuthenticationClient) auth).setAuthenticationPrompt(dialog);
                   ( (PasswordAuthenticationClient) auth)
                   .setPasswordChangePrompt(PasswordChange.getInstance());
                   PasswordChange.getInstance().setParentComponent(
                   SshTerminalPanel.this);
                   }*/

                // Show the implementations dialog
                // if(auth.showAuthenticationDialog()) {
                // Authentication with the details supplied
                try {

                    result = showAuthenticationPrompt(auth); //ssh.authenticate(auth);

                } catch (IllegalArgumentException e) {// Do not use this authentication method!
                    allowed.remove(auth);
                }

                if (result == AuthenticationProtocolState.FAILED) {
                    msg = auth.getMethodName() + " authentication failed, try again?";
                }

                // If the result returned partial success then continue
                if (result == AuthenticationProtocolState.PARTIAL) {
                    // We succeeded so add to the connections authenticaiton
                    // list and continue on to the next one
                    getCurrentConnectionProfile().addAuthenticationMethod(auth);
                    msg = auth.getMethodName() + " authentication succeeded but another is required";
                }

                if (result == AuthenticationProtocolState.COMPLETE) {
                    authenticated = true;

                    //If successfull add to the connections list so we can save later
                    getCurrentConnectionProfile().addAuthenticationMethod(auth);

                    // Set the completed flag
                    completed = true;
                    authenticationComplete(newProfile);
                }

                if (result == AuthenticationProtocolState.CANCELLED) {
                    ssh.disconnect();

                    return false;
                }

                //   }
                //  else {
                // User has cancelled the authenticaiton
                //       closeConnection(true);
                //       return false;
                //  }
            }

            // end of if
        }

        // end of while
        return authenticated;
    } catch (EOFException e) {
        throw new IOException(
                "The remote host has closed the connection.\n\nAs you are authenticating this probably means the server has given up authenticating you.");
    } catch (MessageStoreEOFException e) {
        throw new IOException(
                "The remote host has closed the connection.\n\nAs you are authenticating this probably means the server has given up authenticating you.");
    }
}

From source file:de.cebitec.readXplorer.differentialExpression.plot.DeSeq2GraphicsTopComponent.java

@Override
public void update(Object args) {
    if (args instanceof ChartExporter.ChartExportStatus) {
        final ChartExporter.ChartExportStatus status = (ChartExporter.ChartExportStatus) args;
        try {/*from w ww . ja  v a  2 s.c  o m*/
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    switch (status) {
                    case RUNNING:
                        saveButton.setEnabled(false);
                        svgExportProgressHandle.start();
                        svgExportProgressHandle.switchToIndeterminate();
                        break;
                    case FAILED:
                        messages.setText("The export of the plot failed.");
                    case FINISHED:
                        messages.setText("SVG image saved.");
                        svgExportProgressHandle.switchToDeterminate(100);
                        svgExportProgressHandle.finish();
                        break;
                    }
                }
            });
        } catch (InterruptedException | InvocationTargetException ex) {
            Date currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
            Logger.getLogger(this.getClass().getName()).log(Level.WARNING, ex.getMessage(), currentTimestamp);
        }
    }
}