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:gda.gui.BatonPanel.java

void startMonitoringServer() {
    Thread batonMonitor = ThreadManager.getThread(new Runnable() {
        @Override/*w  w w.j  a  v a 2 s  .c o m*/
        public void run() {

            final long timeoutInMilliseconds = (long) (closeDownOnBatonRenewTimeoutTimeMinutes * 60 * 1000);
            final long closedownTimeoutInMilliseconds = (long) (closeDownOnBatonRenewUserPromptTimeMinutes * 60
                    * 1000);

            // Pretend the last baton renew request was received now.
            batonRenewRequestReceived = System.currentTimeMillis();

            try {
                while (keepMonitoringServer) {

                    Thread.sleep(1000);

                    final long timeSinceRenewRequest = System.currentTimeMillis() - batonRenewRequestReceived;
                    final long timeSinceUserCancelledShutdown = System.currentTimeMillis()
                            - userCancelledShutdown;
                    final long timeSinceLastEvent = Math.min(timeSinceRenewRequest,
                            timeSinceUserCancelledShutdown);

                    if (timeSinceLastEvent >= timeoutInMilliseconds) {

                        // Use invokeAndWait so that the monitoring doesn't continue until the dialog closes
                        SwingUtilities.invokeAndWait(new Runnable() {
                            @Override
                            public void run() {
                                SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

                                    @Override
                                    protected Void doInBackground() throws Exception {
                                        Thread.sleep(closedownTimeoutInMilliseconds);
                                        return null;
                                    }

                                    @Override
                                    protected void done() {
                                        if (isCancelled()) {
                                            userCancelledShutdown = System.currentTimeMillis();
                                        } else {
                                            logger.info(
                                                    "Client closing down due to lack of baton renew requests from the server which is assumed to be dead");
                                            AcquisitionFrame.instance.exit();
                                            keepMonitoringServer = false;
                                        }
                                    }

                                };
                                SwingWorkerProgressDialog dlg = new SwingWorkerProgressDialog(worker, null,
                                        "GDA Shutdown",
                                        "GDA Client has lost connection with the server. It will shut down unless you press cancel...",
                                        true, null, null);
                                dlg.execute();
                            }

                        });
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }, "BatonRequestMonitor");
    batonMonitor.start();
}

From source file:com.conwet.silbops.examples.gui.MainFrame.java

/**
 * @param args the command line arguments
 *//*from ww  w  .j a  v a 2 s  .c  o  m*/
public static void main(String args[]) throws Exception {
    SwingUtilities.invokeAndWait(new Runnable() {

        @Override
        public void run() {
            new MainFrame().setVisible(true);
        }
    });
}

From source file:com.moss.greenshell.wizard.ProcessPanel.java

private void transitionStatic(final JPanel oldView, final JPanel newView, final Runnable followupAction) {
    try {/* w ww .j av a 2 s. c  o  m*/
        Runnable action = new Runnable() {
            public void run() {
                synchronized (view.getActionArea()) {
                    view.getActionArea().removeAll();
                    view.getActionArea().add(newView);
                    view.getActionArea().invalidate();
                    view.validate();
                    if (followupAction != null)
                        followupAction.run();
                }
            }
        };

        if (SwingUtilities.isEventDispatchThread()) {
            action.run();
        } else {
            SwingUtilities.invokeAndWait(action);
        }
    } catch (Exception e) {
        failCatastrophically(e);
    }
}

From source file:com.adito.server.DefaultAditoServerFactory.java

public void createServer(final ClassLoader bootLoader, final String[] args) {
    // This is a hack to allow the Install4J installer to get the java
    // runtime that will be used
    if (args.length > 0 && args[0].equals("--jvmdir")) {
        System.out.println(SystemProperties.get("java.home"));
        System.exit(0);//w w  w .  ja v a2 s  .c o  m
    }
    this.bootLoader = bootLoader;
    useWrapper = System.getProperty("wrapper.key") != null;
    ContextHolder.setContext(this);

    if (useWrapper) {
        WrapperManager.start(this, args);
    } else {
        Integer returnCode = start(args);
        if (returnCode != null) {
            if (gui) {
                if (startupException == null) {
                    startupException = new Exception("An exit code of " + returnCode + " was returned.");
                }
                try {
                    if (SystemProperties.get("os.name").toLowerCase().startsWith("windows")) {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    }
                } catch (ClassNotFoundException e) {
                } catch (InstantiationException e) {
                } catch (IllegalAccessException e) {
                } catch (UnsupportedLookAndFeelException e) {
                }
                String mesg = startupException.getMessage() == null ? "No message supplied."
                        : startupException.getMessage();
                StringBuilder buf = new StringBuilder();
                int l = 0;
                char ch;
                for (int i = 0; i < mesg.length(); i++) {
                    ch = mesg.charAt(i);
                    if (l > 50 && ch == ' ') {
                        buf.append("\n");
                        l = 0;
                    } else {
                        if (ch == '\n') {
                            l = 0;
                        } else {
                            l++;
                        }
                        buf.append(ch);
                    }
                }
                mesg = buf.toString();
                final String fMesg = mesg;
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                            JOptionPane.showMessageDialog(null, fMesg, "Startup Error",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                    });
                } catch (InterruptedException ex) {
                } catch (InvocationTargetException ex) {
                }
            }
            System.exit(returnCode);
        } else {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    if (!shuttingDown) {
                        DefaultAditoServerFactory.this.stop(0);
                    }
                }
            });
        }
    }
}

From source file:edu.mit.fss.examples.member.gui.CommSubsystemPanel.java

@Override
public void timeAdvanced(final SimulationTimeEvent event) {
    // make a copy of state updates to prevent late-running threads from
    // posting out-of-date information
    final Map<Transmitter, Boolean> canReceiveMap = new HashMap<Transmitter, Boolean>();

    // synchronize on map for thread safety
    synchronized (connectSeriesMap) {
        for (Transmitter transmitter : connectSeriesMap.keySet()) {
            canReceiveMap.put(transmitter, subsystem.getReceiver().canReceiveFrom(transmitter));
        }/* w w w  .j  a v  a  2 s  .co  m*/
    }

    // update in event dispatch thread for thread safety
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                for (Transmitter transmitter : canReceiveMap.keySet()) {
                    TimeSeries series = connectSeriesMap.get(transmitter);
                    logger.trace("Adding/updating series " + series.getKey() + ".");
                    series.addOrUpdate(RegularTimePeriod.createInstance(Minute.class, new Date(event.getTime()),
                            TimeZone.getTimeZone("UTC")), canReceiveMap.get(transmitter) ? 1 : 0);
                }
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        logger.error(e);
    }
}

From source file:edu.mit.fss.examples.visual.gui.WorldWindVisualization.java

@Override
public void interactionOccurred(ObjectChangeEvent event) {
    if (event.getObject() instanceof Signal) {
        final Signal signal = (Signal) event.getObject();
        try {/*from  w w w . j a  va2s .  c o  m*/
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    if (signal.getElement() instanceof OrbitalElement) {
                        // trigger transmitting animation
                        optionsPanel.elementTransmitting((OrbitalElement) signal.getElement());
                    } else if (signal.getElement() instanceof SurfaceElement) {
                        // trigger transmitting animation
                        optionsPanel.elementTransmitting((SurfaceElement) signal.getElement());
                    }
                }
            });
        } catch (InvocationTargetException | InterruptedException e) {
            logger.error(e);
        }
    }
}

From source file:net.sf.mzmine.project.impl.StorableScan.java

@Override
public synchronized void addMassList(final @Nonnull MassList massList) {

    // Remove all mass lists with same name, if there are any
    MassList currentMassLists[] = massLists.toArray(new MassList[0]);
    for (MassList ml : currentMassLists) {
        if (ml.getName().equals(massList.getName()))
            removeMassList(ml);//from  w ww . j ava2s  . c  o m
    }

    StorableMassList storedMassList;
    if (massList instanceof StorableMassList) {
        storedMassList = (StorableMassList) massList;
    } else {
        DataPoint massListDataPoints[] = massList.getDataPoints();
        try {
            int mlStorageID = rawDataFile.storeDataPoints(massListDataPoints);
            storedMassList = new StorableMassList(rawDataFile, mlStorageID, massList.getName(), this);
        } catch (IOException e) {
            logger.severe("Could not write data to temporary file " + e.toString());
            return;
        }
    }

    // Add the new mass list
    massLists.add(storedMassList);

    // Add the mass list to the tree model
    MZmineProjectImpl project = (MZmineProjectImpl) MZmineCore.getCurrentProject();

    // Check if we are adding to the current project
    if (Arrays.asList(project.getDataFiles()).contains(rawDataFile)) {
        final RawDataTreeModel treeModel = project.getRawDataTreeModel();
        final MassList newMassList = storedMassList;
        Runnable swingCode = new Runnable() {
            @Override
            public void run() {
                treeModel.addObject(newMassList);
            }
        };

        try {
            if (SwingUtilities.isEventDispatchThread())
                swingCode.run();
            else
                SwingUtilities.invokeAndWait(swingCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.mit.fss.examples.visual.gui.WorldWindVisualization.java

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

        try {//w w w  .  ja v a 2 s  .  c  o m
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    if (element.getFrame() == ReferenceFrame.UNKNOWN) {
                        // do not consider elements with missing frame
                        return;
                    }

                    // update position and size for shapes
                    if (element instanceof OrbitalElement) {
                        final OrbitalElement orbital = (OrbitalElement) element;

                        // determine cartesian position of element
                        Vector3D cartPosition = null;
                        try {
                            Transform t = orbital.getFrame().getOrekitFrame().getTransformTo(wwj, date);
                            cartPosition = t.transformPosition(orbital.getPosition());
                        } catch (OrekitException e) {
                            logger.error(e);
                        }

                        // convert cartesian to geodetic position
                        final Position geoPosition = wwd.getModel().getGlobe()
                                .computePositionFromPoint(convert(cartPosition));

                        // compute footprint radius using field-of-view angle
                        double earthRadius = wwd.getModel().getGlobe().getRadiusAt(geoPosition.getLatitude(),
                                geoPosition.getLongitude());
                        final double footRadius = FastMath.max(0,
                                FastMath.min(earthRadius, geoPosition.getElevation() * FastMath
                                        .tan(FastMath.toRadians(optionsPanel.getFieldOfView(orbital) / 2))));

                        optionsPanel.getOrbitalShape(orbital).setCenterPosition(geoPosition);
                        optionsPanel.getFootprintShape(orbital)
                                .setCenter(new LatLon(geoPosition.getLatitude(), geoPosition.getLongitude()));
                        optionsPanel.getFootprintShape(orbital).setMajorRadius(footRadius);
                        optionsPanel.getFootprintShape(orbital).setMinorRadius(footRadius);
                    } else if (element instanceof SurfaceElement) {
                        final SurfaceElement surface = (SurfaceElement) element;
                        optionsPanel.getSurfaceMarker(surface).setPosition(Position.fromDegrees(
                                surface.getLatitude(), surface.getLongitude(), surface.getAltitude()));
                    }
                }
            });
        } catch (InvocationTargetException | InterruptedException e) {
            logger.error(e);
        }
    }
}

From source file:com.mgmtp.jfunk.core.JFunk.java

private static List<File> requestScriptsViaGui() {
    final List<File> scripts = new ArrayList<>();

    try {//w  w w .  j  a  v a  2  s  .c o  m
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                JFileChooser fileChooser = new JFileChooser(System.getProperty(JFunkConstants.USER_DIR));
                fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                fileChooser.setMultiSelectionEnabled(true);
                fileChooser.setPreferredSize(new Dimension(800, 450));
                int i = fileChooser.showOpenDialog(null);

                if (i == JFileChooser.APPROVE_OPTION) {
                    File[] files = fileChooser.getSelectedFiles();
                    scripts.addAll(Arrays.asList(files));
                }
            }
        });
    } catch (Exception e) {
        LOG.error("Error while requesting scripts via GUI", e);
    }

    return scripts;
}

From source file:com.univocity.app.swing.DataAnalysisWindow.java

protected void executeProcess(String processName) {
    final Runnable process = config.getProcess(processName);
    getGlass().activate("Executing process: '" + processName + "'...");

    Thread thread = new Thread() {
        @Override/*from   w  w w .j ava  2s .c o m*/
        public void run() {
            try {
                long start = System.currentTimeMillis();
                SwingUtilities.invokeAndWait(process);
                long timeTaken = System.currentTimeMillis() - start;
                setStatus("Completed.", "Took " + timeTaken / 1000 + " seconds (" + timeTaken + " ms)");
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                setStatus("Interrupted", "");
            } catch (InvocationTargetException ie) {
                WindowUtils.showErrorMessage(DataAnalysisWindow.this, ie.getCause());
                setStatus("Interrupted", "");
            } finally {
                getGlass().deactivate();
            }
            System.gc();
        }
    };
    thread.start();
}