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:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java

private void showInGuiProcessingLogList() throws InterruptedException, InvocationTargetException {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override/* w  w w. java2s .  c om*/
        public void run() {
            gui.listHandlingProgressBar.setValue(30);
            gui.listHandlingProgressBar.setIndeterminate(true);
            gui.listHandlingProgressBar
                    .setString(I18n.text("Contacting remote system for complete log file list..."));

            gui.listHandlingProgressBar.setValue(40);
            gui.listHandlingProgressBar.setIndeterminate(false);
            gui.listHandlingProgressBar.setString(I18n.text("Processing log list..."));
        }
    });
}

From source file:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java

private void showInGuiUpdatingLogsInfo() throws InterruptedException, InvocationTargetException {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override/* w w w  .  j  av a 2 s . com*/
        public void run() {
            gui.listHandlingProgressBar.setValue(70);
            gui.listHandlingProgressBar.setIndeterminate(false);
            gui.listHandlingProgressBar.setString(I18n.text("Updating logs info..."));
        }
    });
}

From source file:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java

private void showInGuiUpdatingGui() throws InterruptedException, InvocationTargetException {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override//www  .  j  a va 2  s. c  om
        public void run() {
            gui.listHandlingProgressBar.setValue(90);
            gui.listHandlingProgressBar.setIndeterminate(false);
            gui.listHandlingProgressBar.setString(I18n.text("Updating GUI..."));
        }
    });
}

From source file:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java

private void showInGuiDone() throws InterruptedException, InvocationTargetException {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override/*  ww w  .ja va 2  s  . c o  m*/
        public void run() {
            gui.listHandlingProgressBar.setValue(100);
            gui.listHandlingProgressBar.setIndeterminate(false);
            gui.listHandlingProgressBar.setString(I18n.text("Done"));
        }
    });
}

From source file:ro.nextreports.designer.action.chart.OpenChartAction.java

public void actionPerformed(ActionEvent e) {

    if (testInner) {
        if (NextReportsUtil.isInnerEdit()) {
            return;
        }//from www. ja v a 2 s  .  c o  m
    }

    if (MessageUtil.showReconnect()) {
        return;
    }

    if (chartName == null) {
        BrowserPanel browser = new BrowserPanel(BrowserPanel.CHART_BROWSER);
        dialog = new BrowserDialog(browser);
        dialog.pack();
        dialog.setResizable(false);
        Show.centrateComponent(Globals.getMainFrame(), dialog);
        dialog.setVisible(true);

        // On double click in OpenChart dialog the dialog is closed and set to null
        // see comment #2
        if (dialog != null) {
            if (dialog.okPressed()) {
                chartName = browser.getSelectedName();
                chartPath = browser.getSelectedFilePath();
            } else {
                return;
            }
        }
    }

    Globals.getReportUndoManager().discardAllEdits();

    if (chartName == null) {
        return;
    }

    // comment #2  : for double click in OpenChart dialog
    if ((dialog != null) && dialog.isVisible()) {
        dialog.dispose();
        dialog = null;
    }

    final QueryBuilderPanel builderPanel = Globals.getMainFrame().getQueryBuilderPanel();

    if (!NextReportsUtil.saveYesNoCancel(I18NSupport.getString("open.chart"))) {
        return;
    }

    if (chartPath != null) {
        byte status = NextChartUtil.isValidChartVersion(chartPath);
        if (NextChartUtil.CHART_INVALID_NEWER == status) {
            Show.error(I18NSupport.getString("chart.version.invalid.newer",
                    ReleaseInfoAdapter.getVersionNumber()));
            return;
        }
    }

    if (resetServerChart) {
        Globals.resetServerFile();
    }

    Globals.setReportLoaded(false);
    Globals.setChartLoaded(false);

    Thread executorThread = new Thread(new Runnable() {

        public void run() {
            UIActivator activator = new UIActivator(Globals.getMainFrame(),
                    I18NSupport.getString("load.chart"));
            activator.start();

            try {
                Globals.getMainMenuBar().enableLayoutPerspective(true);
                Globals.getMainToolBar().enableLayoutPerspective(true);

                final Chart chart = ChartUtil.loadChart(chartPath);
                if (chart == null) {
                    if (activator != null) {
                        activator.stop();
                        activator = null;
                    }
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            Show.error(I18NSupport.getString("could.not.load.chart"));
                        }
                    });
                    return;
                }

                I18nManager.getInstance().setKeys(chart.getI18nkeys());
                I18nManager.getInstance().setLanguages(chart.getLanguages());
                I18nManager.getInstance().setCurrentLanguage(I18nUtil.getDefaultLanguage(chart));

                final Report report = chart.getReport();
                try {
                    itemMap = TableUtil.getItemMap(report);
                } catch (Exception ex) {
                    // designer cannot be created (tables not found)
                    if (activator != null) {
                        activator.stop();
                        activator = null;
                    }
                    int option = JOptionPane.showConfirmDialog(Globals.getMainFrame(),
                            "<html>" + I18NSupport.getString("designer.load.error") + "<br>"
                                    + I18NSupport.getString("designer.load.error.table") + "<br>"
                                    + I18NSupport.getString("designer.load.error.edit.mode") + "</html>",
                            "", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
                    if (option != JOptionPane.YES_OPTION) {
                        return;
                    } else {
                        report.setSql(report.getQuery().toString());
                    }
                }

                if (Globals.getConnection() != null) {
                    List<NameType> columns = new ArrayList<NameType>();
                    try {
                        columns = ReportLayoutUtil.getAllColumnsForReport(chart.getReport());
                    } catch (Exception ex) {
                        LOG.error(ex.getMessage(), ex);
                        error = true;
                        errorMessage = I18NSupport.getString("could.not.load.chart.error.columns") + "\r\n"
                                + ex.getMessage();
                    }
                    Globals.getChartDesignerPanel().getPropertiesPanel().setColumns(columns);
                    Globals.getChartLayoutPanel().setColumns(columns);
                }

                if (activator != null) {
                    activator.stop();
                    activator = null;
                }

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

                        builderPanel.clear(true);

                        if (report.getSql() != null) {
                            builderPanel.selectSQLViewTab();
                            builderPanel.setUserSql(report.getSql());
                            Globals.setInitialQuery(report.getSql());
                        } else if (report.getQuery() != null) {
                            builderPanel.drawDesigner(report, itemMap);
                            itemMap.clear();
                            Globals.setInitialQuery(report.getQuery().toString());
                        }
                        builderPanel.setParameters(report.getParameters());
                        builderPanel.selectTreeNode(chartName, DBObject.CHARTS);

                        Globals.setCurrentQueryName(null);
                        Globals.setCurrentQueryAbsolutePath(null);
                        Globals.setCurrentChartName(chartName);
                        Globals.setCurrentChartAbsolutePath(chartPath);

                        builderPanel.loadChart(chart);
                        Globals.getMainMenuBar().newChartActionUpdate();
                        Globals.getMainToolBar().newChartActionUpdate();

                        Globals.setOriginalSql(Globals.getMainFrame().getQueryBuilderPanel().getUserSql());
                        Globals.setChartLoaded(true);

                        if (error) {
                            new OpenQueryPerspectiveAction().actionPerformed(null);
                            Show.error(errorMessage);
                        }

                    }
                });
            } catch (Exception ex) {
                LOG.error(ex.getMessage(), ex);
                Show.error(ex);
            } finally {
                chartName = null;
                if (activator != null) {
                    activator.stop();
                }
            }

        }
    }, "NEXT : " + getClass().getSimpleName());
    executorThread.start();
}

From source file:ro.nextreports.designer.datasource.ConnectionDialog.java

public void actionPerformed(ActionEvent ev) {
    String s = ev.getActionCommand();
    if (s.equals("ConnectOk")) {

        Thread executorThread = new Thread(new Runnable() {

            public void run() {

                UIActivator activator = new UIActivator(ConnectionDialog.this,
                        I18NSupport.getString("connect.to", mName.getText()));
                activator.start();/*from  w w  w  .  j a v  a 2 s .  co m*/

                try {
                    DataSource ds = new DataSource();
                    ds.setName(mName.getText());
                    Object type = types.getSelectedItem();
                    if (type != null) {
                        ds.setType((String) type);
                    }
                    ds.setDriver(mDriver.getText());
                    ds.setPassword(String.valueOf(mPassword.getPassword()));
                    ds.setUrl(mURL.getText());
                    ds.setUser(mUser.getText());
                    ds.setProperties(p);
                    mConnection = Globals.createTempConnection(ds);

                    DBViewer v = new DefaultDBViewer();
                    final DBInfo info = v.getDBInfo(DBInfo.INFO, mConnection);
                    final String success = I18NSupport.getString("connection.dialog.succes");

                    SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                            txaStatus.setText(success + "\r\n" + info.getInfo());
                        }
                    });

                    // do the disconnect here too
                    if (mConnection != null) {
                        try {
                            mConnection.close();
                            //txaStatus.setText("Disconnected.");
                            mConnection = null;
                        } catch (final SQLException e) {
                            SwingUtilities.invokeAndWait(new Runnable() {
                                public void run() {
                                    txaStatus.setText(e.toString());
                                }
                            });
                        } catch (Exception ex) {
                            LOG.error(ex.getMessage(), ex);
                            ex.printStackTrace();
                            mConnection = null;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LOG.error(e.getMessage(), e);
                    txaStatus.setText(e.toString());
                } finally {
                    if (activator != null) {
                        activator.stop();
                    }
                }

            }
        }, "NEXT : " + getClass().getSimpleName());
        executorThread.start();

        /*
        } else if (s.equals("AddDriver")) {
                
        final JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.addChoosableFileFilter(new JarFilter());
        String path = ReporterPreferencesManager.getInstance().loadParameter(ReporterPreferencesManager.JAR_PATH_KEY);
        if (path != null) {
        chooser.setSelectedFile(new File(path));
        }
        int returnVal = chooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        ReporterPreferencesManager.getInstance().storeParameter(ReporterPreferencesManager.JAR_PATH_KEY,
                file.getAbsolutePath());
        try {
            DriverPath.addEntry(file.getAbsolutePath());
        } catch (IOException ex) {
            LOG.error(ex.getMessage(), ex);
            ex.printStackTrace();
        }
                                   
        // TODO remove this option (put all drivers in jdbc-drivers folder)
        try {
           LauncherClassLoader launcherClassLoader = (LauncherClassLoader) ConnectionDialog.class.getClassLoader();
           if (file.isDirectory()) {
          launcherClassLoader.loadJars(file);
           } else {
          launcherClassLoader.loadJar(file);
           }
        } catch (Exception ex) {
           Show.error(ex);
        }                
        }
        */
    } else if (s.equals("Disconnect")) {
        if (mConnection != null) {
            try {
                mConnection.close();
                txaStatus.setText(I18NSupport.getString("connection.dialog.disconnected"));
                mConnection = null;
                //Globals.setConnection(mConnection);
            } catch (SQLException e) {
                txaStatus.setText(e.toString());
                mConnection = null;
            }
        }

    } else if (s.equals("Properties")) {

        if (!mDriver.getText().equals(CSVDialect.DRIVER_CLASS)) {
            Show.info(I18NSupport.getString("connection.dialog.noproperties"));
            return;
        }

        if ((p == null) || p.isEmpty()) {
            if (oldDataSource != null) {
                p = oldDataSource.getProperties();
            }
            if ((p == null) || p.isEmpty()) {
                p = getDefaultCsvProperties();
            }
        }

        final DataSourcePropertyPanel panel = new DataSourcePropertyPanel(p);
        BaseDialog dialog = new BaseDialog(panel, I18NSupport.getString("connection.dialog.properties"), true) {
            protected boolean ok() {
                Properties local = panel.getLocalProperties();
                for (Object key : local.keySet()) {
                    p.put(key, p.get(key));
                }
                return true;
            }
        };
        dialog.setPreferredSize(new Dimension(300, 200));
        dialog.setLocationRelativeTo(Globals.getMainFrame());
        dialog.setVisible(true);

    } else if (s.equals("AddDataSource")) {
        addedDataSource = null;
        DataSource ds = new DataSource();

        if (mName.getText().trim().equals("")) {
            Show.info(I18NSupport.getString("connection.dialog.name.enter"));
            return;
        }

        ds.setName(mName.getText());
        ds.setDriver(mDriver.getText());
        ds.setType((String) types.getSelectedItem());
        ds.setUrl(mURL.getText());
        ds.setPassword(String.valueOf(mPassword.getPassword()));
        ds.setUser(mUser.getText());
        ds.setStatus(DataSourceType.DISCONNECTED);
        ds.setProperties(p);

        //System.out.println(ds);
        DataSourceManager manager = DefaultDataSourceManager.getInstance();
        try {
            if (oldDataSource == null) {
                added = true;
                newName = ds.getName();
                manager.addDataSource(ds);
                Globals.getMainFrame().getQueryBuilderPanel().addDataSource(ds.getName());
                addedDataSource = ds;
            } else {
                try {
                    System.out.println(">> ds.getName()=" + ds.getName() + " oldDataSource.getName()="
                            + oldDataSource.getName());
                    oldName = oldDataSource.getName();
                    newName = ds.getName();
                    manager.modifyDataSource(oldDataSource, ds);
                    if (!ds.getName().equals(oldDataSource.getName())) {
                        Globals.getMainFrame().getQueryBuilderPanel().modifyDataSource(oldName, newName);
                    }
                    modified = true;
                } catch (ModificationException e) {
                    Show.info(e.getMessage());
                }
            }
            manager.save();
            this.dispose();
            afterSave();
        } catch (NonUniqueException e) {
            Show.info(I18NSupport.getString("connection.dialog.exists", ds.getName()));
        }
    }
}

From source file:ro.nextreports.designer.querybuilder.RuntimeParametersPanel.java

private void parameterSelection(final int pos, final Object obj) {

    QueryParameter param = paramList.get(pos);
    parametersValues.put(param.getName(), obj);
    final Map<String, QueryParameter> dependents = ParameterManager.getInstance()
            .getChildDependentParameters(param);
    if (dependents.size() > 0) {

        Thread executorThread = new Thread(new Runnable() {

            public void run() {
                UIActivator activator = new UIActivator(
                        (JDialog) SwingUtilities.getWindowAncestor(RuntimeParametersPanel.this),
                        I18NSupport.getString("run.load.dependent.parameters"));
                activator.start();/*w ww.  j  a va  2s. com*/

                try {
                    for (final QueryParameter qp : dependents.values()) {
                        Map<String, QueryParameter> map = ParameterManager.getInstance()
                                .getParentDependentParameters(qp);
                        Map<String, Object> vals = new HashMap<String, Object>();
                        boolean selected = true;
                        for (QueryParameter p : map.values()) {
                            Object v = parametersValues.get(p.getName());
                            if (((obj instanceof Object[]) && (((Object[]) obj).length == 0)) || (v == null)) {
                                selected = false;
                            }
                            vals.put(p.getName(), v);
                        }

                        final List<IdName> values = new ArrayList<IdName>();
                        // all parent parameters selected
                        if (selected) {
                            Query query = new Query(qp.getSource());
                            // no count and no check for other parameters completition
                            QueryExecutor executor = new QueryExecutor(query, map, vals, con, false, false,
                                    false);
                            executor.setTimeout(Globals.getQueryTimeout());
                            executor.setMaxRows(0);
                            QueryResult qr = executor.execute();
                            //int count = qr.getRowCount();
                            int columnCount = qr.getColumnCount();

                            // two columns in manual select source!!!
                            //for (int i = 0; i < count; i++) {
                            while (qr.hasNext()) {
                                IdName in = new IdName();
                                in.setId((Serializable) qr.nextValue(0));
                                if (columnCount == 1) {
                                    in.setName((Serializable) qr.nextValue(0));
                                } else {
                                    in.setName((Serializable) qr.nextValue(1));
                                }
                                values.add(in);
                            }
                            Collections.sort(values, new IdNameComparator(qp.getOrderBy()));
                            qr.close();
                        }
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                ArrayList<Serializable> defaultValues = qp.getDefaultValues();
                                if ((qp.getDefaultSourceValues() != null)
                                        && (qp.getDefaultSourceValues().size() > 1)) {
                                    defaultValues = qp.getDefaultSourceValues();
                                }
                                initParameterValue(getComponent(qp), values, qp.getName(), defaultValues);
                            }
                        });

                    }

                } catch (Exception ex) {
                    LOG.error(ex.getMessage(), ex);
                    ex.printStackTrace();
                } finally {
                    if (activator != null) {
                        activator.stop();
                    }
                }

            }
        }, "NEXT : " + getClass().getSimpleName());
        executorThread.setPriority(EngineProperties.getRunPriority());
        executorThread.start();
    }

}

From source file:statechum.analysis.learning.Visualiser.java

/** Removes the two windows displaying Jung graphs.
 *//*from   w  w w.  ja  v  a 2  s  .  c  om*/
public static void disposeFrame() {
    boolean anythingNeedsDisposing = false;
    for (int i = 0; i < graphWindow.length && !anythingNeedsDisposing; ++i)
        if (graphWindow[i] != null)
            anythingNeedsDisposing = true;
    if (anythingNeedsDisposing) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    for (int i = 0; i < graphWindow.length; ++i)
                        if (graphWindow[i] != null) {
                            graphWindow[i].setVisible(false);
                            graphWindow[i].dispose();
                            graphWindow[i] = null;
                        }
                }
            });
        } catch (InterruptedException e) {
            // cannot do much about this
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // cannot do much about this
            e.printStackTrace();
        }
    }
}

From source file:uk.ac.liverpool.narrative.SolutionGraphics.java

public static void main(final String[] args) throws Exception {

    System.out.println("Current invocation: " + Arrays.toString(args));
    final SolutionGraphics sg = new SolutionGraphics();
    JCommander jc = new JCommander(sg);
    jc.setProgramName("BranchingStoryGenerator");
    try {//from   w ww  . jav  a  2  s.  co  m
        jc.parse(args);
    } catch (ParameterException x) {
        jc.usage();
        System.out.println(x.getMessage());
        System.exit(-1);
    }
    sg.setTemplate(Template.readTemplate(new File(sg.templateFilePath)));

    SwingUtilities.invokeAndWait(sg);

    // sg.sg.simulateCleanup();

    sg.sg.simulateCleanup();
    BranchingSearch.setTemplate(sg.template);
    sg.sg.usm = BranchingSearch.CompareMethod.Jacard;
    sg.sg.doCleanup();
    // sg.sg.usm = BranchingSearch.CompareMethod.Jacard;
    // System.out.println(sg.sg.solutions.size());
    // sg.sg.doCleanup();
    // System.out.println(sg.sg.solutions.size());
    sg.sg.populateGraph();
    if (sg.charFilter != null) {
        sg.sg.keepCharacterBranching(sg.charFilter);
    }
    sg.sg.cleanupLoops(4);
    sg.printSolutions();

    SwingUtilities.invokeAndWait(new Runnable() {

        @Override
        public void run() {
            sg.paintMinSpanningTree();

        }
    });
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            sg.createVisualStateGraph(false, 900);

        }
    });

    try {
        sg.sg.runStory(sg.template, System.out, System.in);
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:utybo.branchingstorytree.swing.impl.BRMFileClient.java

private void invokeAndWait(Runnable r) {
    try {//from  w w  w.  ja  v a  2  s. c om
        SwingUtilities.invokeAndWait(r);
    } catch (InvocationTargetException | InterruptedException e) {
        OpenBST.LOG.warn("Failed Swing invoke", e);
    }
}