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:com.offbynull.peernetic.debug.visualizer.JGraphXVisualizer.java

@Override
public void visualize(final Recorder recorder, final VisualizerEventListener listener) {
    if (consumed.getAndSet(true)) {
        throw new IllegalStateException();
    }/*from w  w w  .j a  va 2s  .c om*/

    try {
        SwingUtilities.invokeAndWait(() -> {
            textOutputArea.append(JGraphXVisualizer.class.getSimpleName() + " started.\n\n");
            JGraphXVisualizer.this.listener.set(listener);
            JGraphXVisualizer.this.recorder.set(recorder);
            frame.setVisible(true);
        });
    } catch (InterruptedException | InvocationTargetException ex) {
        throw new RuntimeException("Visualize failed", ex);
    }
}

From source file:edu.mit.fss.examples.member.gui.PowerSubsystemPanel.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 double storedEnergy = subsystem.getPowerStored();
    final double powerGeneration = subsystem.getPowerGeneration();
    final double powerConsumption = subsystem.getTotalPowerConsumption();

    // update in event dispatch thread for thread safety
    try {/*from  ww w. j a va2  s  .  c  o  m*/
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                storageSeries.addOrUpdate(RegularTimePeriod.createInstance(Minute.class,
                        new Date(event.getTime()), TimeZone.getTimeZone("UTC")), storedEnergy);
                generationSeries.addOrUpdate(RegularTimePeriod.createInstance(Minute.class,
                        new Date(event.getTime()), TimeZone.getTimeZone("UTC")), powerGeneration);
                consumptionSeries.addOrUpdate(RegularTimePeriod.createInstance(Minute.class,
                        new Date(event.getTime()), TimeZone.getTimeZone("UTC")), powerConsumption);
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        logger.error(e);
    }
}

From source file:components.TumbleItem.java

public void init() {
    loadAppletParameters();/*from w  ww. j  av  a  2s.c  o  m*/

    //Execute a job on the event-dispatching thread:
    //creating this applet's GUI.
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                createGUI();
            }
        });
    } catch (Exception e) {
        System.err.println("createGUI didn't successfully complete");
    }

    //Set up timer to drive animation events.
    timer = new Timer(speed, this);
    timer.setInitialDelay(pause);
    timer.start();

    //Start loading the images in the background.
    worker.execute();
}

From source file:Console.java

public void run() {
    try {/*from  w ww  . j  av  a2  s  .co  m*/
        /*
         * Loop as long as there is output from the process to be displayed or as long as the
         * process is still running even if there is presently no output.
         */
        while (output.ready() || processRunning) {

            // If there is output get it and display it.
            if (output.ready()) {
                char[] array = new char[255];
                int num = output.read(array);
                if (num != -1) {
                    String s = new String(array, 0, num);
                    data.append(s);
                    SwingUtilities.invokeAndWait(new ConsoleWrite(cta, s));
                }
            }
        }
    } catch (Exception e) {
        System.err.println("Problem writing to standard output.");
        System.err.println(e);
    }
}

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

@Override
public void objectChanged(final ObjectChangeEvent event) {
    for (ObjectChangeListener l : listenerList.getListeners(ObjectChangeListener.class)) {
        l.objectChanged(event);//from   w  ww.jav a  2 s.c o  m
    }
    // update in event dispatch thread for thread safety
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                if (connectSeriesMap.containsKey(event.getObject())) {
                    // update transmitter series key because transmitter
                    // name may have changed
                    Transmitter tx = (Transmitter) event.getObject();
                    logger.trace("Updating series key for transmitter " + tx.getName() + ".");
                    TimeSeries series = connectSeriesMap.get(event.getObject());
                    series.setKey(tx.getName());
                } else if (event.getObject() != subsystem.getTransmitter()
                        && event.getObject() instanceof Transmitter
                        && !connectSeriesMap.containsKey(event.getObject())) {
                    // add new series for transmitter
                    Transmitter tx = (Transmitter) event.getObject();
                    logger.trace("Adding series for transmitter " + tx.getName() + ".");
                    TimeSeries series = new TimeSeries(tx.getName());
                    connectSeriesMap.put(tx, series);
                    connectDataset.addSeries(series);
                }
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        logger.error(e);
    }
}

From source file:eu.delving.sip.base.VisualFeedback.java

private void execWait(final Runnable runnable) {
    try {//from   w  ww  . j av a2s.co  m
        Runnable wrapper = new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } catch (Exception e) {
                    alert(e.toString(), e); // todo: better idea?
                }
            }
        };
        SwingUtilities.invokeAndWait(wrapper);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.iritgo.aktario.client.gui.UserLoginHelper.java

static private void connectAndGo(String username, String password, final UserLoginPane loginPane) {
    CommandTools.performAsync(new ConnectToServer());
    CommandTools.performAsync(new UserLogin(username, password));

    CommandTools.performAsync(new Command() {
        @Override//from www  .  java  2  s.c o m
        public void perform() {
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(loginPane != null ? loginPane.getPanel() : null,
                                Engine.instance().getResourceService().getString("aktario.serverNotAvailable"),
                                Engine.instance().getResourceService().getString("app.title"),
                                JOptionPane.OK_OPTION);
                    }
                });
            } catch (InterruptedException x) {
            } catch (InvocationTargetException x) {
            }

            CommandTools.performAsync(new ShowDialog("AktarioUserLoginDialog"));
        }

        @Override
        public boolean canPerform() {
            return AppContext.instance().isConnectedWithServer() == false;
        }
    });
}

From source file:com.clank.launcher.swing.SwingHelper.java

/**
 * Show a message dialog using/* w  w w  . j a  v a 2  s .c  o  m*/
 * {@link javax.swing.JOptionPane#showMessageDialog(java.awt.Component, Object, String, int)}.
 *
 * <p>The dialog will be shown from the Event Dispatch Thread, regardless of the
 * thread it is called from. In either case, the method will block until the
 * user has closed the dialog (or dialog creation fails for whatever reason).</p>
 *
 * @param parentComponent the frame from which the dialog is displayed, otherwise
 *                        null to use the default frame
 * @param message the message to display
 * @param title the title string for the dialog
 * @param messageType see {@link javax.swing.JOptionPane#showMessageDialog(java.awt.Component, Object, String, int)}
 *                    for available message types
 */
public static void showMessageDialog(final Component parentComponent, @NonNull final String message,
        @NonNull final String title, final String detailsText, final int messageType) {

    if (SwingUtilities.isEventDispatchThread()) {
        // To force the label to wrap, convert the message to broken HTML
        String htmlMessage = "<html><div style=\"width: 250px\">" + htmlEscape(message);

        JPanel panel = new JPanel(new BorderLayout(0, detailsText != null ? 20 : 0));

        // Add the main message
        panel.add(new JLabel(htmlMessage), BorderLayout.NORTH);

        // Add the extra details
        if (detailsText != null) {
            JTextArea textArea = new JTextArea(_("errors.reportErrorPreface") + detailsText);
            JLabel tempLabel = new JLabel();
            textArea.setFont(tempLabel.getFont());
            textArea.setBackground(tempLabel.getBackground());
            textArea.setTabSize(2);
            textArea.setEditable(false);
            textArea.setComponentPopupMenu(TextFieldPopupMenu.INSTANCE);

            JScrollPane scrollPane = new JScrollPane(textArea);
            scrollPane.setPreferredSize(new Dimension(350, 120));
            panel.add(scrollPane, BorderLayout.CENTER);
        }

        JOptionPane.showMessageDialog(parentComponent, panel, title, messageType);
    } else {
        // Call method again from the Event Dispatch Thread
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    showMessageDialog(parentComponent, message, title, detailsText, messageType);
                }
            });
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.hartveld.commons.test.swing.AbstractSwingFrameTest.java

private void createAndAcquireLock() throws RuntimeException {
    LOG.trace("Creating and acquiring lock ...");

    checkIsNotEDT();/*w  w w.j  ava2 s.c om*/

    lock = new ReentrantLock();

    try {
        SwingUtilities.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                LOG.trace("Attempting to acquire lock ...");
                if (!lock.tryLock()) {
                    throw new RuntimeException("Failed to acquire UI lock");
                }
            }
        });
    } catch (InterruptedException | InvocationTargetException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}

From source file:com.aw.swing.mvp.binding.BindingComponent.java

protected void updateUI() {
    if (!initialized && !uiReadOnly) {
        return;/*from  ww w. j a  va  2 s  .c o  m*/
    }
    if (SwingUtilities.isEventDispatchThread()) {
        updateUIInternal();
    } else {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    updateUIInternal();
                }
            });
        } catch (Throwable e) {
            throw new AWSystemException("Problems updating the UI:" + this, e);
        }

    }
}