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.thelq.stackexchange.dbimport.Utils.java

/**
 * SwingUtilities.invokeAndWait exceptions rethrown as unchecked RuntimeExceptions.
 * Saves an extra layer of indentation/*from   w  w w  . java2  s . co  m*/
 * @param runnable 
 */
public static void invokeAndWaitUnchecked(Runnable runnable) {
    try {
        SwingUtilities.invokeAndWait(runnable);
    } catch (Exception e) {
        throw new RuntimeException("Cannot wait for invokeAndWait", e);
    }
}

From source file:org.tinymediamanager.core.movie.tasks.MovieScrapeTask.java

@Override
protected void doInBackground() {
    initThreadPool(3, "scrape");
    start();/*from  w  w  w  .ja  va 2 s.  com*/

    smartScrapeList = new ArrayList<>(0);

    for (int i = 0; i < moviesToScrape.size(); i++) {
        Movie movie = moviesToScrape.get(i);
        submitTask(new Worker(movie));
    }
    waitForCompletionOrCancel();

    // initiate smart scrape
    if (!smartScrapeList.isEmpty() && !GraphicsEnvironment.isHeadless()) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    for (Movie movie : smartScrapeList) {
                        MovieChooserDialog dialogMovieChooser = new MovieChooserDialog(movie,
                                smartScrapeList.size() > 1 ? true : false);
                        if (!dialogMovieChooser.showDialog()) {
                            break;
                        }
                    }
                }
            });
        } catch (Exception e) {
            LOGGER.error("SmartScrape crashed " + e.getMessage());
        }
    }

    if (MovieModuleManager.MOVIE_SETTINGS.getSyncTrakt()) {
        TmmTask task = new SyncTraktTvTask(moviesToScrape, null);
        TmmTaskManager.getInstance().addUnnamedTask(task);
    }

    LOGGER.info("Done scraping movies)");
}

From source file:org.tros.logo.swing.LogoPanel.java

@Override
public void repaint() {
    if (SwingUtilities.isEventDispatchThread()) {
        LogoPanel.super.repaint();
    } else {/*from w w w  . ja v a2  s. c  o  m*/
        java.util.prefs.Preferences prefs = java.util.prefs.Preferences.userNodeForPackage(LogoMenuBar.class);
        if (prefs.getBoolean(LogoMenuBar.WAIT_FOR_REPAINT, true)) {
            try {
                SwingUtilities.invokeAndWait(new Runnable() {

                    @Override
                    public void run() {
                        LogoPanel.super.repaint();
                    }
                });
            } catch (InterruptedException | InvocationTargetException ex) {
                org.tros.utils.logging.Logging.getLogFactory().getLogger(LogoPanel.class).fatal(null, ex);
            }
        } else {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    LogoPanel.super.repaint();
                }
            });
        }
    }
}

From source file:org.ut.biolab.medsavant.client.query.QueryViewController.java

private void applySearchConditions() {

    Thread t = new Thread(new Runnable() {
        @Override//from  w  ww  .  j av a2  s .c  o m
        public void run() {
            try {
                Condition c;
                c = getSQLConditionsFrom(rootGroup);
                if (c == null) {
                    c = ConditionUtils.TRUE_CONDITION;
                }

                //LOG.info(c.toString());
                SwingUtilities.invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        warningText.setVisible(false);
                        applyButton.setText("Searching...");
                        applyButton.setEnabled(false);
                        applyButton.updateUI();
                    }
                });
                FilterController.getInstance().setConditions(c);
                SwingUtilities.invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        applyButton.setText("Search");
                        applyButton.updateUI();
                    }
                });
            } catch (final IllegalArgumentException ex) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        DialogUtils.displayError("Search Error", ex.getMessage());
                    }
                });
            } catch (Exception ex) {
                LOG.info(ex);
                ex.printStackTrace();
                DialogUtils.displayException("Error", "There was an error performing your search", ex);
            }
        }
    });
    t.start();

}

From source file:org.yccheok.jstock.gui.news.StockNewsJFrame.java

private void initComponents() {
    setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
    setAlwaysOnTop(true);/* w  w w  .j  a v a  2s . c om*/
    setAutoRequestFocus(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent evt) {
            formWindowClosing(evt);
        }
    });

    addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosed(java.awt.event.WindowEvent evt) {
        }

        public void windowClosing(java.awt.event.WindowEvent evt) {
            NewsTask task = StockNewsJFrame.this.newsTask;
            if (task != null) {
                task.cancel(true);
            }
        }

        public void windowDeiconified(java.awt.event.WindowEvent evt) {
        }

        public void windowIconified(java.awt.event.WindowEvent evt) {
        }
    });

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            // JFXPanel => Scene => SplitPane:
            //      Left  (news List)       => StackPane => ListView / ProgressIndicator
            //      Right (HTML content)    => TabPane => Tab => StackPane => WebView / ProgressBar

            splitPane = new SplitPane();
            scene = new Scene(splitPane);

            scene.getStylesheets()
                    .add(StockNewsJFrame.class.getResource("StockNewsJFrame.css").toExternalForm());
            jfxPanel.setScene(scene);

            // Left component: News List
            messages_o = FXCollections.observableArrayList();
            newsListView = new ListView<>(messages_o);
            newsListView.setId("news-listview");

            stackPane.setId("parent-stackPane");
            stackPane.getChildren().addAll(newsListView, progressIn);

            splitPane.getItems().add(stackPane);
            SplitPane.setResizableWithParent(stackPane, Boolean.FALSE);

            // show progress indicator when loading
            progressIn.setMaxWidth(100);
            progressIn.setMaxHeight(100);
            progressIn.setVisible(true);
            newsListView.setVisible(true);

            newsListView.setCellFactory(new Callback<ListView<FeedItem>, ListCell<FeedItem>>() {
                @Override
                public ListCell<FeedItem> call(ListView<FeedItem> list) {
                    return new DisplayNewsCard();
                }
            });

            // register event listener: add tab for news HTML content
            newsListView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if (event.getClickCount() >= 1) {
                        final FeedItem msg = newsListView.getSelectionModel().getSelectedItem();
                        if (msg == null) {
                            return;
                        }

                        final URL link = msg.getLink();
                        if (link == null || link.getHost() == null) {
                            return;
                        }

                        if (stockNewsContent == null) {
                            stackPane.setPrefWidth(stackPane.getWidth());
                            stackPane.setMaxWidth(stackPane.getWidth());
                            stackPane.setMinWidth(stackPane.getWidth() / 5);

                            try {
                                SwingUtilities.invokeAndWait(new Runnable() {
                                    @Override
                                    public void run() {
                                        // resize JFrame first
                                        StockNewsJFrame.this.setSize(fullSize.width, fullSize.height);

                                        java.awt.Insets in = StockNewsJFrame.this.getInsets();
                                        jfxPanel.setSize(StockNewsJFrame.this.getWidth() - in.left - in.right,
                                                jfxPanel.getHeight());

                                        java.awt.Insets in2 = jfxPanel.getInsets();

                                        // calculate width & height, but not resize in AWT event dispatching thread
                                        // javafx.scene.control.SplitPane should only be accessed from JavaFX Application Thread
                                        splitPaneWidth = jfxPanel.getWidth() - in2.left - in2.right;
                                        splitPaneHeight = jfxPanel.getHeight() - in2.top - in2.bottom;
                                    }
                                });
                            } catch (InterruptedException | InvocationTargetException ex) {
                                log.error(null, ex);
                            }

                            // resize to full screen size of jfxPanel
                            splitPane.resize(splitPaneWidth, splitPaneHeight);

                            stockNewsContent = new StockNewsContent();
                            splitPane.getItems().add(stockNewsContent.tabPane);
                            splitPane.setDividerPositions(0.5f);

                            stockNewsContent.tabPane.getSelectionModel().selectedItemProperty()
                                    .addListener(new ChangeListener<Tab>() {
                                        @Override
                                        public void changed(ObservableValue<? extends Tab> observable,
                                                Tab oldTab, Tab newTab) {
                                            int i = stockNewsContent.tabPane.getSelectionModel()
                                                    .getSelectedIndex();
                                            if (i < 0) {
                                                return;
                                            }

                                            jFrameTitle = stockNewsContent.tabsInfo.get(i).second;

                                            SwingUtilities.invokeLater(new Runnable() {
                                                @Override
                                                public void run() {
                                                    StockNewsJFrame.this.setTitle(jFrameTitle);
                                                }
                                            });
                                        }
                                    });
                        }
                        stockNewsContent.addNewsTab(link, StringEscapeUtils.unescapeHtml(msg.getTitle()));
                    }
                }
            });

            retrieveNewsInBackground();
        }
    });

    this.add(jfxPanel, BorderLayout.CENTER);
    this.setVisible(true);
}

From source file:org.yccheok.jstock.gui.SaveToCloudJDialog.java

private boolean promptUserToContinue(final List<Country> countryWithWatchlistFilesBeingIgnored) {
    if (countryWithWatchlistFilesBeingIgnored.isEmpty()) {
        // No watchlist file(s) is ignored.
        return true;
    }//from w w w . ja va2  s .  c  om

    int size = countryWithWatchlistFilesBeingIgnored.size();
    final String message;
    final String title;
    if (size == 1) {
        message = MessageFormat.format(
                MessagesBundle.getString("question_message_too_many_stocks_during_save_to_cloud_template"),
                countryWithWatchlistFilesBeingIgnored.get(0));
        title = MessagesBundle.getString("question_title_too_many_stocks_during_save_to_cloud");
    } else {
        message = MessageFormat.format(
                MessagesBundle.getString(
                        "question_message_too_many_stocks_in_multiple_countries_during_save_to_cloud_template"),
                size);
        title = MessagesBundle
                .getString("question_title_too_many_stocks_in_multiple_countries_during_save_to_cloud");
    }

    // Ensure thread safety when we pop up confirmation dialog box. Is it
    // possible to cause deadlock due to invokeAndWait?
    final int[] choice = new int[1];
    choice[0] = JOptionPane.NO_OPTION;
    if (SwingUtilities.isEventDispatchThread()) {
        choice[0] = JOptionPane.showConfirmDialog(SaveToCloudJDialog.this, message, title,
                JOptionPane.YES_NO_OPTION);
    } else {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    choice[0] = JOptionPane.showConfirmDialog(SaveToCloudJDialog.this, message, title,
                            JOptionPane.YES_NO_OPTION);
                }
            });
        } catch (InterruptedException ex) {
            log.error(null, ex);
        } catch (InvocationTargetException ex) {
            log.error(null, ex);
        }
    }
    return choice[0] == JOptionPane.YES_OPTION;
}

From source file:org.zaproxy.zap.extension.quickstart.AttackThread.java

private SiteNode accessNode(URL url) {
    SiteNode startNode = null;//from  w w w. java2s .  c o  m
    // Request the URL
    try {
        final HttpMessage msg = new HttpMessage(new URI(url.toString(), true),
                extension.getModel().getOptionsParam().getConnectionParam());
        getHttpSender().sendAndReceive(msg, true);

        if (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
            extension.notifyProgress(Progress.failed, Constant.messages
                    .getString("quickstart.progress.failed.code", msg.getResponseHeader().getStatusCode()));

            return null;
        }

        if (msg.getResponseHeader().isEmpty()) {
            extension.notifyProgress(Progress.failed);
            return null;
        }

        ExtensionHistory extHistory = ((ExtensionHistory) Control.getSingleton().getExtensionLoader()
                .getExtension(ExtensionHistory.NAME));
        extHistory.addHistory(msg, HistoryReference.TYPE_PROXIED);

        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                // Needs to be done on the EDT
                Model.getSingleton().getSession().getSiteTree().addPath(msg.getHistoryRef());
            }
        });

        for (int i = 0; i < 10; i++) {
            startNode = Model.getSingleton().getSession().getSiteTree()
                    .findNode(new URI(url.toString(), false));
            if (startNode != null) {
                break;
            }
            try {
                sleep(200);
            } catch (InterruptedException e) {
                // Ignore
            }
        }
    } catch (UnknownHostException e1) {
        ConnectionParam connectionParam = Model.getSingleton().getOptionsParam().getConnectionParam();
        if (connectionParam.isUseProxyChain()
                && connectionParam.getProxyChainName().equalsIgnoreCase(e1.getMessage())) {
            extension.notifyProgress(Progress.failed, Constant.messages
                    .getString("quickstart.progress.failed.badhost.proxychain", e1.getMessage()));
        } else {
            extension.notifyProgress(Progress.failed,
                    Constant.messages.getString("quickstart.progress.failed.badhost", e1.getMessage()));
        }
    } catch (URIException e) {
        extension.notifyProgress(Progress.failed,
                Constant.messages.getString("quickstart.progress.failed.reason", e.getMessage()));
    } catch (Exception e1) {
        logger.error(e1.getMessage(), e1);
        extension.notifyProgress(Progress.failed,
                Constant.messages.getString("quickstart.progress.failed.reason", e1.getMessage()));
        return null;
    }
    return startNode;
}

From source file:pcgen.gui2.PCGenFrame.java

/**
 * Asynchronously load the sources required for a character and then load the character.
 * @param pcgFile The character to be loaded.
 *//*from  ww  w.j a v  a 2 s. co m*/
private void loadSourcesThenCharacter(final File pcgFile) {
    new Thread() {

        @Override
        public void run() {
            try {
                sourceLoader.join();
                SwingUtilities.invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        final String msg = LanguageBundle.getFormattedString("in_loadPcLoadingFile",
                                pcgFile.getName());
                        statusBar.startShowingProgress(msg, false);
                        statusBar.getProgressBar().getModel().setRangeProperties(0, 1, 0, 2, false);
                        statusBar.getProgressBar().setString(LanguageBundle.getString("in_loadPcOpening"));
                    }
                });
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            CharacterManager.openCharacter(pcgFile, PCGenFrame.this, currentDataSetRef.get());
                            statusBar.getProgressBar().getModel().setRangeProperties(1, 1, 0, 2, false);
                        } catch (Exception e) {
                            Logging.errorPrint("Error loading character: " + pcgFile.getName(), e);
                        } finally {
                            statusBar.endShowingProgress();
                        }
                    }

                });
            } catch (InterruptedException ex) {
                //Do nothing
            } catch (InvocationTargetException e1) {
                Logging.errorPrint("Error showing progress bar.", e1);
            }
        }

    }.start();
}

From source file:pipeline.GUI_utils.ListOfPointsView.java

private void setupTableModel(List<T> pointList) {
    tableModel = points.getBeanTableModel();
    try {//from   ww  w  . j a  v a  2s  .c o m
        Runnable r = () -> {
            synchronized (modelSemaphore) {
                tableModel.removeTableModelListener(ListOfPointsView.this);
                tableModel.addTableModelListener(ListOfPointsView.this);
                if (table != null) {
                    table.silenceUpdates.incrementAndGet();
                    table.setModel(tableModel);
                    table.needToInitializeFilterModel = true;
                    table.initializeFilterModel();
                    setSpreadsheetColumnEditorAndRenderer();
                    modelForColumnDescriptions = new dataModelAllEditable(1, tableModel.getColumnCount());
                    @SuppressWarnings("unchecked")
                    Vector<String> rowVector0 = (Vector<String>) modelForColumnDescriptions.getDataVector()
                            .get(0);
                    for (int j = 0; j < tableModel.getColumnCount(); j++) {
                        // FIXME This ignores the names the user may have set
                        rowVector0.setElementAt(tableModel.getColumnName(j), j);
                    }
                    modelForColumnDescriptions.fireTableDataChanged();
                    table.silenceUpdates.decrementAndGet();
                    ((AbstractTableModel) table.getModel()).fireTableStructureChanged();
                }
            }
        };
        if (SwingUtilities.isEventDispatchThread())
            r.run();
        else
            SwingUtilities.invokeAndWait(r);
    } catch (InvocationTargetException | InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:pl.otros.logview.BufferingLogDataCollectorProxyTest.java

@BeforeMethod
public void initTest() throws InterruptedException, InvocationTargetException {
    configuration = new BaseConfiguration();
    configuration.setProperty(ConfKeys.TAILING_PANEL_PLAY, true);

    delegate = new ProxyLogDataCollector();
    bufferingLogDataCollectorProxy = new BufferingLogDataCollectorProxy(delegate, sleepTime, configuration);
    // Initialize swing thread
    SwingUtilities.invokeAndWait(new Runnable() {

        @Override/*from  w w  w .  j a v  a  2  s .c  o m*/
        public void run() {

        }
    });
}