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:pl.otros.logview.gui.actions.read.ProgressWatcher.java

public void updateProgress(final String message, final int current, final int min, final int max) {
    Runnable r = new Runnable() {

        @Override/*w  ww .  j av  a 2s .  co m*/
        public void run() {
            progressBar.setIndeterminate(false);
            progressBar.setMaximum(max);
            progressBar.setMinimum(min);
            progressBar.setValue(current);
            progressBar.setString(message);
            // refreshProgress = false;

        }

    };
    try {
        SwingUtilities.invokeAndWait(r);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

}

From source file:pl.otros.logview.gui.LogViewMainFrame.java

/**
 * @param args porgram CLI arguments//w w w.j  av a  2 s. c  o m
 * @throws InitializationException
 * @throws InvocationTargetException
 * @throws InterruptedException
 */
public static void main(final String[] args)
        throws InitializationException, InterruptedException, InvocationTargetException {
    if (args.length > 0 && "-batch".equals(args[0])) {
        try {
            String[] batchArgs = new String[args.length - 1];
            System.arraycopy(args, 1, batchArgs, 0, batchArgs.length);
            BatchProcessor.main(batchArgs);
        } catch (IOException e) {
            System.err.println("Error during batch processing: " + e.getMessage());
            e.printStackTrace();
        } catch (ConfigurationException e) {
            System.err.println("Error during batch processing: " + e.getMessage());
            e.printStackTrace();
        }
        return;
    }
    SingleInstanceRequestResponseDelegate singleInstanceRequestResponseDelegate = SingleInstanceRequestResponseDelegate
            .getInstance();
    singleInstance = SingleInstance.request("OtrosLogViewer", singleInstanceRequestResponseDelegate,
            singleInstanceRequestResponseDelegate, args);
    if (singleInstance == null) {
        LOGGER.info("OtrosLogViewer is already running, params send using requestAction");
        System.exit(0);
    }
    GuiJulHandler handler = new GuiJulHandler();
    handler.setLevel(Level.ALL);
    Logger olvLogger = Logger.getLogger("pl.otros.logview");
    olvLogger.setLevel(Level.ALL);
    olvLogger.addHandler(handler);
    LOGGER.info("Starting application");
    OtrosSplash.setMessage("Starting application");
    OtrosSplash.setMessage("Loading configuration");
    final XMLConfiguration c = getConfiguration("config.xml");
    if (!c.containsKey(ConfKeys.UUID)) {
        c.setProperty(ConfKeys.UUID, UUID.randomUUID().toString());
    }
    IconsLoader.loadIcons();
    OtrosSplash.setMessage("Loading icons");
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            try {
                OtrosSplash.setMessage("Loading L&F");
                String lookAndFeel = c.getString("lookAndFeel",
                        "com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
                LOGGER.config("Initializing look and feelL: " + lookAndFeel);
                PlasticLookAndFeel.setTabStyle(Plastic3DLookAndFeel.TAB_STYLE_METAL_VALUE);
                UIManager.setLookAndFeel(lookAndFeel);
            } catch (Throwable e1) {
                LOGGER.warning("Cannot initialize LookAndFeel: " + e1.getMessage());
            }
            try {
                final DataConfiguration c1 = new OtrosConfiguration(c);
                final LogViewMainFrame mf = new LogViewMainFrame(c1);
                // mf.exitAction was instantiated in the constructor (previous line)
                // Not sure retrieving this from most appropriate Apache config
                // object.
                mf.exitAction.setConfirm(c.getBoolean("generalBehavior.confirmExit", true));
                /* TODO:  Implement User Preferences screen or checkbox on exit widget
                 * that will update the same config object something like:
                 *     c.setProperty("generalBehavior.confirmExit", newValue);
                 */
                mf.addComponentListener(new ComponentAdapter() {
                    @Override
                    public void componentResized(ComponentEvent e) {
                        c.setProperty("gui.state", mf.getExtendedState());
                        if (mf.getExtendedState() == Frame.NORMAL) {
                            c.setProperty("gui.width", mf.getWidth());
                            c.setProperty("gui.height", mf.getHeight());
                        }
                    }

                    @Override
                    public void componentMoved(ComponentEvent e) {
                        c.setProperty("gui.location.x", mf.getLocation().x);
                        c.setProperty("gui.location.y", mf.getLocation().y);
                    }
                });
                mf.addWindowListener(mf.exitAction);
                SingleInstanceRequestResponseDelegate.openFilesFromStartArgs(mf.otrosApplication,
                        Arrays.asList(args), mf.otrosApplication.getAppProperties().getCurrentDir());
            } catch (InitializationException e) {
                LOGGER.log(Level.SEVERE, "Cannot initialize main frame", e);
            }
        }
    });
}

From source file:pl.otros.vfs.browser.auth.AbstractUiUserAuthenticator.java

@Override
public UserAuthenticationData requestAuthentication(Type[] types) {
    try {/*from   w  ww .ja  va 2 s .  c  o m*/
        Runnable doRun = new Runnable() {
            @Override
            public void run() {
                if (saveCredentialsCheckBox == null) {
                    saveCredentialsCheckBox = new JCheckBox(Messages.getMessage("authenticator.savePassword"),
                            true);
                }
                JPanel authOptionPanel = getOptionsPanel();

                JPanel panel = new JPanel(new BorderLayout());
                panel.add(authOptionPanel);
                panel.add(saveCredentialsCheckBox, BorderLayout.SOUTH);

                String[] options = { Messages.getMessage("general.okButtonText"),
                        Messages.getMessage("general.cancelButtonText") };
                int showConfirmDialog = JOptionPane.showOptionDialog(null, panel,
                        Messages.getMessage("authenticator.enterCredentials"), JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
                if (showConfirmDialog != JOptionPane.OK_OPTION) {
                    throw new AuthorisationCancelledException("Authorization cancelled by user");
                }

                data = new UserAuthenticationDataWrapper();
                getAuthenticationData(data);
            }
        };
        if (SwingUtilities.isEventDispatchThread()) {
            doRun.run();
        } else {
            SwingUtilities.invokeAndWait(doRun);
        }
    } catch (Exception e) {
        if (Throwables.getRootCause(e) instanceof AuthorisationCancelledException) {
            throw (AuthorisationCancelledException) Throwables.getRootCause(e);
        }
    }

    return data;
}

From source file:pl.otros.vfs.browser.demo.TestBrowser.java

public static void main(final String[] args)
        throws InterruptedException, InvocationTargetException, SecurityException, IOException {
    if (args.length > 1)
        throw new IllegalArgumentException(
                "SYNTAX:  java... " + TestBrowser.class.getName() + " [initialPath]");

    SwingUtilities.invokeAndWait(new Runnable() {

        @Override//from w w  w  .  j  a  v  a  2s  . c  o  m
        public void run() {
            tryLoadSubstanceLookAndFeel();
            final JFrame f = new JFrame("OtrosVfsBrowser demo");
            Container contentPane = f.getContentPane();
            contentPane.setLayout(new BorderLayout());
            DataConfiguration dc = null;
            final PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
            File favoritesFile = new File("favorites.properties");
            propertiesConfiguration.setFile(favoritesFile);
            if (favoritesFile.exists()) {
                try {
                    propertiesConfiguration.load();
                } catch (ConfigurationException e) {
                    e.printStackTrace();
                }
            }
            dc = new DataConfiguration(propertiesConfiguration);
            propertiesConfiguration.setAutoSave(true);
            final VfsBrowser comp = new VfsBrowser(dc, (args.length > 0) ? args[0] : null);
            comp.setSelectionMode(SelectionMode.FILES_ONLY);
            comp.setMultiSelectionEnabled(true);
            comp.setApproveAction(new AbstractAction(Messages.getMessage("demo.showContentButton")) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    FileObject[] selectedFiles = comp.getSelectedFiles();
                    System.out.println("Selected files count=" + selectedFiles.length);
                    for (FileObject selectedFile : selectedFiles) {
                        try {
                            FileSize fileSize = new FileSize(selectedFile.getContent().getSize());
                            System.out.println(selectedFile.getName().getURI() + ": " + fileSize.toString());
                            byte[] bytes = readBytes(selectedFile.getContent().getInputStream(), 150 * 1024l);
                            JScrollPane sp = new JScrollPane(new JTextArea(new String(bytes)));
                            JDialog d = new JDialog(f);
                            d.setTitle("Content of file: " + selectedFile.getName().getFriendlyURI());
                            d.getContentPane().add(sp);
                            d.setSize(600, 400);
                            d.setVisible(true);
                        } catch (Exception e1) {
                            LOGGER.error("Failed to read file", e1);
                            JOptionPane.showMessageDialog(f,
                                    (e1.getMessage() == null) ? e1.toString() : e1.getMessage(), "Error",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            });

            comp.setCancelAction(new AbstractAction(Messages.getMessage("general.cancelButtonText")) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    f.dispose();
                    try {
                        propertiesConfiguration.save();
                    } catch (ConfigurationException e1) {
                        e1.printStackTrace();
                    }
                    System.exit(0);
                }
            });
            contentPane.add(comp);

            f.pack();
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        }
    });
}

From source file:processing.app.Sketch.java

private void setCurrentCode(int which, boolean forceUpdate) {
    // if current is null, then this is the first setCurrent(0)
    if (!forceUpdate && (currentIndex == which) && (current != null)) {
        return;/*from  w  w w  .ja  v  a  2 s.  c  o m*/
    }

    // get the text currently being edited
    if (current != null) {
        current.getCode().setProgram(editor.getText());
        current.setSelectionStart(editor.getSelectionStart());
        current.setSelectionStop(editor.getSelectionStop());
        current.setScrollPosition(editor.getScrollPosition());
    }

    current = (SketchCodeDocument) data.getCode(which).getMetadata();
    currentIndex = which;

    if (SwingUtilities.isEventDispatchThread()) {
        editor.setCode(current);
    } else {
        try {
            SwingUtilities.invokeAndWait(() -> editor.setCode(current));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    editor.header.rebuild();
}

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

private void addTheNewFoldersAnFillTheReturnedExistentAndNewLists(LinkedHashMap<FTPFile, String> retList,
        LinkedList<LogFolderInfo> existenteLogFoldersFromServer,
        LinkedList<LogFolderInfo> newLogFoldersFromServer)
        throws InterruptedException, InvocationTargetException {
    for (String newLogName : retList.values()) {
        if (stopLogListProcessing)
            return;

        final LogFolderInfo newLogDir = new LogFolderInfo(newLogName);
        if (gui.logFolderList.containsFolder(newLogDir)) {
            existenteLogFoldersFromServer.add(gui.logFolderList.getFolder((newLogDir.getName())));
        } else {//from   w  w w  .jav a2 s .c o  m
            newLogFoldersFromServer.add(newLogDir);
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    gui.logFolderList.addFolder(newLogDir);
                }
            });
        }
    }
    // msgPanel.writeMessageTextln("Logs Folders: " + logFolderList.myModel.size());
}

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

private void showInGuiStarting() throws InterruptedException, InvocationTargetException {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override//from  w w  w .j av  a2 s. co  m
        public void run() {
            gui.listHandlingProgressBar.setValue(0);
            gui.listHandlingProgressBar.setString(I18n.text("Starting..."));
        }
    });
}

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

private void showInGuiConnectingToServers() throws InterruptedException, InvocationTargetException {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override/* w w  w . j av a2s.  c o  m*/
        public void run() {
            gui.listHandlingProgressBar.setValue(10);
            gui.listHandlingProgressBar.setIndeterminate(true);
            gui.listHandlingProgressBar
                    .setString(I18n.text("Connecting to remote system for log list update..."));
        }
    });
}

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

private void showInGuiNumberOfLogsFromServers(LinkedHashMap<FTPFile, String> retList)
        throws InterruptedException, InvocationTargetException {
    if (retList.size() == 0) {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override//from w w w  . j a v  a2s .  c o m
            public void run() {
                gui.listHandlingProgressBar.setValue(100);
                gui.listHandlingProgressBar.setIndeterminate(false);
                gui.listHandlingProgressBar.setString(I18n.text("No logs..."));
            }
        });
    } else {
        final String msg1 = I18n.textf("Log Folders: %numberoffolders", retList.size());
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                // listHandlingProgressBar.setValue(10);
                // listHandlingProgressBar.setIndeterminate(true);
                gui.listHandlingProgressBar.setString(msg1);
            }
        });
    }
}

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

private void showInGuiFiltering() throws InterruptedException, InvocationTargetException {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override/*from  w w  w .  j  a va2s  .  c om*/
        public void run() {
            gui.listHandlingProgressBar.setValue(20);
            gui.listHandlingProgressBar.setIndeterminate(false);
            gui.listHandlingProgressBar.setString(I18n.text("Filtering list..."));
        }
    });
}