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.uncommons.watchmaker.swing.evolutionmonitor.EvolutionMonitor.java

/**
 * Creates an EvolutionMonitor with a second panel that displays a graphical
 * representation of the fittest candidate in the population.
 * @param renderer Renders a candidate solution as a JComponent.
 * @param islands Whether the monitor should be configured for displaying data from
 * {@link org.uncommons.watchmaker.framework.islands.IslandEvolution}.  Set this
 * parameter to false when using a standard {@link org.uncommons.watchmaker.framework.EvolutionEngine}
 *///from w w  w. j a v a  2s .c  o m
public EvolutionMonitor(final Renderer<? super T, JComponent> renderer, boolean islands) {
    this.islands = islands;
    if (SwingUtilities.isEventDispatchThread()) {
        init(renderer);
    } else {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    init(renderer);
                }
            });
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException(ex);
        } catch (InvocationTargetException ex) {
            throw new IllegalStateException(ex);
        }
    }
}

From source file:org.usfirst.frc.team2084.neuralnetwork.HeadingNeuralNetworkTrainer.java

public HeadingNeuralNetworkTrainer() {
    outputGraphNetworkSeries = new XYSeries("Network Prediction");
    outputGraphDataSeries = new XYSeries("Error");
    final XYSeriesCollection data = new XYSeriesCollection();
    data.addSeries(outputGraphDataSeries);
    data.addSeries(outputGraphNetworkSeries);
    outputGraph = ChartFactory.createXYLineChart("Error vs. Output", "Time", "Error", data,
            PlotOrientation.VERTICAL, true, true, false);

    NumberAxis xAxis = new NumberAxis();
    xAxis.setRange(new Range(-Math.PI, Math.PI));
    xAxis.setAutoRange(false);/*from ww w .  j  a va  2  s . c  om*/
    NumberAxis yAxis = new NumberAxis();
    yAxis.setRange(new Range(-1, 1));

    XYPlot plot = (XYPlot) outputGraph.getPlot();
    plot.setDomainAxis(xAxis);
    plot.setRangeAxis(yAxis);

    network = new Network(new int[] { 1, 5, 1 }, eta, momentum, new TransferFunction.HyperbolicTangent());

    try {
        SwingUtilities.invokeAndWait(() -> {
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final Container content = frame.getContentPane();
            content.setLayout(new BorderLayout());

            outputGraphPanel = new ChartPanel(outputGraph);
            outputGraphPanel.setDomainZoomable(false);
            outputGraphPanel.setRangeZoomable(false);
            graphPanel.add(outputGraphPanel);

            graphPanel.setLayout(new GridLayout(1, 1));
            content.add(graphPanel, BorderLayout.CENTER);
            {

                JLabel etaLabel = new JLabel("Eta:");
                etaLabel.setLabelFor(etaField);
                etaField.setText(Double.toString(network.getEta()));
                etaField.setColumns(5);
                etaField.addPropertyChangeListener("value",
                        (evt) -> eta = ((Number) evt.getNewValue()).doubleValue());
                controlPanel.add(etaLabel);
                controlPanel.add(etaField);

                JLabel momentumLabel = new JLabel("Momentum:");
                momentumLabel.setLabelFor(etaField);
                momentumField.setText(Double.toString(network.getMomentum()));
                momentumField.setColumns(5);
                momentumField.addPropertyChangeListener("value",
                        (evt) -> momentum = ((Number) evt.getNewValue()).doubleValue());
                controlPanel.add(momentumLabel);
                controlPanel.add(momentumField);

                JLabel iterationsLabel = new JLabel("Iterations:");
                iterationsLabel.setLabelFor(iterationsField);
                iterationsField.setText(Integer.toString(iterations));
                iterationsField.setColumns(10);
                iterationsField.addPropertyChangeListener("value",
                        (evt) -> iterations = ((Number) evt.getNewValue()).intValue());
                controlPanel.add(iterationsLabel);
                controlPanel.add(iterationsField);
            }

            chooseDataButton.addActionListener((e) -> {
                if (dataDirectoryChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
                    dataDirectory = dataDirectoryChooser.getSelectedFile();
                    displayData();
                }
            });
            controlPanel.add(chooseDataButton);

            trainButton.addActionListener((e) -> trainNetwork());
            controlPanel.add(trainButton);

            saveButton.addActionListener((e) -> {
                saveNetwork();
            });
            controlPanel.add(saveButton);

            content.add(controlPanel, BorderLayout.SOUTH);

            dataDirectoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        });
    } catch (InvocationTargetException | InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:biomine.bmvis2.pipeline.sources.QueryGraphSource.java

@Override
public BMGraph getBMGraph() throws GraphOperationException {
    try {/*from  ww w.  jav a  2 s  .com*/
        if (fetch == null) {
            fetch = new CrawlerFetch(query, neighborhood, database);
        }
        if (ret == null) {
            final JDialog dial = new JDialog((JFrame) null);

            dial.setTitle("BMVIS II - Query to database");
            dial.setSize(400, 200);
            dial.setMinimumSize(new Dimension(400, 200));
            dial.setResizable(false);
            final JTextArea text = new JTextArea();
            text.setEditable(false);

            dial.add(text);
            text.setText("...");

            class Z {
                Exception runExc = null;
            }

            final Z z = new Z();
            Runnable fetchThread = new Runnable() {
                public void run() {
                    try {
                        long startTime = System.currentTimeMillis();
                        while (!fetch.isDone()) {
                            fetch.update();
                            Thread.sleep(500);
                            long time = System.currentTimeMillis();
                            long elapsed = time - startTime;

                            if (elapsed > 30000) {
                                throw new GraphOperationException("Timeout while querying " + query);
                            }
                            final String newText = fetch.getState() + ":\n" + fetch.getMessages();
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    text.setText(newText);
                                }
                            });
                        }

                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                dial.setVisible(false);
                            }
                        });

                    } catch (Exception e) {
                        z.runExc = e;
                    }

                }

            };

            new Thread(fetchThread).start();
            dial.setModalityType(ModalityType.APPLICATION_MODAL);
            dial.setVisible(true);
            ret = fetch.getBMGraph();
            if (ret == null)
                throw new GraphOperationException(fetch.getMessages());
            if (z.runExc != null) {
                if (z.runExc instanceof GraphOperationException)
                    throw (GraphOperationException) z.runExc;
                else
                    throw new GraphOperationException(z.runExc);
            }
        }

    } catch (IOException e) {
        throw new GraphOperationException(e);
    }
    updateInfo();
    return ret;
}

From source file:net.sourceforge.jasa.view.SupplyAndDemandFrame.java

public void onInteractionsFinished(final InteractionsFinishedEvent event) {
    if (panel.isShowing()) {
        try {//from   w  w w. j  a  v a2  s . co  m
            updateData();
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    dataset.datasetChanged(event);
                }
            });
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (InvocationTargetException e) {
            logger.error(e);
            throw new RuntimeException(e);
        }
    }
}

From source file:com.meghnasoft.async.AbstractAsynchronousAction.java

/**
 * This is constructor for AbstractAsynchronousAction class.
 *
 * @param name The name of the action, passed to the super class AbstractAction
 *//*from w w  w . j  a  va  2  s  . c  om*/
public AbstractAsynchronousAction(String name) {
    this();
    putValue(Action.NAME, name);

    final Runnable doFinished = new Runnable() {
        public void run() {
            finished();
            firePropertyChange("enabled", Boolean.FALSE, Boolean.TRUE);
        }
    };

    this.asynchronousActionRunnable = new Runnable() {
        public void run() {
            try {
                setTaskOutput(asynchronousActionPerformed(lastActionEvent));
            } catch (Exception excp) {
                log.error("Aysynchronous action got exception", excp);
            } finally {
                threadVar.clear();

                try {
                    SwingUtilities.invokeAndWait(doFinished);
                } catch (InterruptedException ex) {
                    if (log.isDebugEnabled()) {
                        log.debug("Asynchronous action got " + "interrupted exception", ex);
                    }
                } catch (InvocationTargetException ex) {
                    if (log.isDebugEnabled()) {
                        log.debug("Asynchronous action got invocation " + "target exception", ex);
                    }
                }
            }
        }
    };
}

From source file:com.qspin.qtaste.ui.MainPanel.java

public void launch() throws InterruptedException, InvocationTargetException {
    SwingUtilities.invokeAndWait(new Runnable() {

        public void run() {
            setQSpinTheme();//from w  ww . j a  v a2s.c  o m
            genUI();
        }
    });
}

From source file:net.sourceforge.atunes.kernel.modules.process.AudioFileTransferProcess.java

@Override
protected boolean runProcess() {
    boolean errors = false;
    File destination = new File(getDestination());
    long bytesTransferred = 0;
    boolean ignoreAllErrors = false;
    addInfoLog(StringUtils.getString("Transferring ", this.filesToTransfer.size(), " files to ", destination));
    for (Iterator<AudioFile> it = this.filesToTransfer.iterator(); it.hasNext() && !cancel;) {
        AudioFile file = it.next();//from  w  ww.ja v  a 2s. c  om
        final List<Exception> thrownExceptions = new ArrayList<Exception>();
        File transferredFile = transferAudioFile(destination, file, thrownExceptions);
        filesTransferred.add(transferredFile);
        if (!thrownExceptions.isEmpty()) {
            for (Exception e : thrownExceptions) {
                addErrorLog(e);
            }
            if (!ignoreAllErrors) {
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            userSelectionWhenErrors = (String) VisualHandler.getInstance().showMessage(
                                    StringUtils.getString(LanguageTool.getString("ERROR"), ": ",
                                            thrownExceptions.get(0).getMessage()),
                                    LanguageTool.getString("ERROR"), JOptionPane.ERROR_MESSAGE,
                                    new String[] { LanguageTool.getString("IGNORE"),
                                            LanguageTool.getString("IGNORE_ALL"),
                                            LanguageTool.getString("CANCEL") });
                        }
                    });
                } catch (InterruptedException e1) {
                    // Do nothing
                } catch (InvocationTargetException e1) {
                    // Do nothing
                }
                if (LanguageTool.getString("IGNORE").equals(userSelectionWhenErrors)) {
                    // Do nothing, let execution continue
                } else if (LanguageTool.getString("IGNORE_ALL").equals(userSelectionWhenErrors)) {
                    // Don't display more error messages
                    ignoreAllErrors = true;
                } else if (LanguageTool.getString("CANCEL").equals(userSelectionWhenErrors)) {
                    // Only in this case set errors to true to force refresh in other case
                    errors = true;

                    // Don't continue
                    break;
                }
            }
        }
        // Add size to bytes transferred
        bytesTransferred += file.getFile().length();
        setCurrentProgress(bytesTransferred);
    }
    addInfoLog("Transfer process done");
    return !errors;
}

From source file:CheckThreadViolationRepaintManager.java

static void repaintTest() {
    try {/* w  w  w .j ava 2s . com*/
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                test = new JButton();
                test.setSize(100, 100);
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
    // repaint(Rectangle) should be ok
    test.repaint(test.getBounds());
    test.repaint(0, 0, 100, 100);
    test.repaint();
}

From source file:de.codesourcery.eve.skills.ui.components.impl.BlueprintChooserComponent.java

public BlueprintChooserComponent() {
    filterThread = new DelayedMethodInvokerThread(200) {

        @Override/*  w  w  w.  ja  va 2 s .c  o  m*/
        protected void invokeDelayedMethod() throws Exception {
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    nameFilterChanged();
                }
            });
        }

    };
    filterThread.start();

    byNameTextField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            filterThread.eventOccured();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            filterThread.eventOccured();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            filterThread.eventOccured();
        }
    });

    this.treeModelBuilder = new BlueprintTreeModelBuilder(this.dataModelProvider) {
        @Override
        protected List<InventoryType> getMembers(MarketGroup group) {
            final String name = byNameTextField.getText();
            if (name != null && name.length() >= MIN_NAME_LENGTH) {
                substringFilterUsed = true;
                return dataModelProvider.getStaticDataModel().getInventoryTypesWithBlueprints(group, name);
            }
            return dataModelProvider.getStaticDataModel().getInventoryTypesWithBlueprints(group);
        }

        @Override
        protected IViewFilter<ITreeNode> getViewFilter() {
            final IViewFilter<ITreeNode> superFilter = super.getViewFilter();
            return new AbstractViewFilter<ITreeNode>() {

                @Override
                public boolean isHiddenUnfiltered(ITreeNode value) {
                    if (superFilter.isHidden(value)) {
                        return true;
                    }

                    final String name = byNameTextField.getText();
                    if (name != null && name.length() >= MIN_NAME_LENGTH) {
                        final Blueprint bp = getSelectedBlueprint(value);
                        return bp != null && !bp.getName().toLowerCase().contains(name.toLowerCase());
                    }
                    return false;
                }
            };
        }
    };
    this.treeModelBuilder.attach(tree);
}

From source file:net.pms.newgui.Wizard.java

public static void run(final PmsConfiguration configuration) {
    // Total number of questions
    int numberOfQuestions = Platform.isMac() ? 4 : 5;

    // The current question number
    int currentQuestionNumber = 1;

    String status = new StringBuilder().append(Messages.getString("Wizard.2")).append(" %d ")
            .append(Messages.getString("Wizard.4")).append(" ").append(numberOfQuestions).toString();

    Object[] okOptions = { Messages.getString("Dialog.OK") };

    Object[] yesNoOptions = { Messages.getString("Dialog.YES"), Messages.getString("Dialog.NO") };

    Object[] networkTypeOptions = { Messages.getString("Wizard.8"), Messages.getString("Wizard.9"),
            Messages.getString("Wizard.10") };

    if (!Platform.isMac()) {
        // Ask if they want UMS to start minimized
        int whetherToStartMinimized = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.3"),
                String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[1]);

        if (whetherToStartMinimized == JOptionPane.YES_OPTION) {
            configuration.setMinimized(true);
        } else if (whetherToStartMinimized == JOptionPane.NO_OPTION) {
            configuration.setMinimized(false);
        }/*w w w . j av a  2s. c o m*/
    }

    // Ask if their network is wired, etc.
    int networkType = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.7"),
            String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, networkTypeOptions, networkTypeOptions[1]);

    switch (networkType) {
    case JOptionPane.YES_OPTION:
        // Wired (Gigabit)
        configuration.setMaximumBitrate("0");
        configuration.setMPEG2MainSettings("Automatic (Wired)");
        configuration.setx264ConstantRateFactor("Automatic (Wired)");
        break;
    case JOptionPane.NO_OPTION:
        // Wired (100 Megabit)
        configuration.setMaximumBitrate("90");
        configuration.setMPEG2MainSettings("Automatic (Wired)");
        configuration.setx264ConstantRateFactor("Automatic (Wired)");
        break;
    case JOptionPane.CANCEL_OPTION:
        // Wireless
        configuration.setMaximumBitrate("30");
        configuration.setMPEG2MainSettings("Automatic (Wireless)");
        configuration.setx264ConstantRateFactor("Automatic (Wireless)");
        break;
    default:
        break;
    }

    // Ask if they want to hide advanced options
    int whetherToHideAdvancedOptions = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.11"),
            String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[0]);

    if (whetherToHideAdvancedOptions == JOptionPane.YES_OPTION) {
        configuration.setHideAdvancedOptions(true);
    } else if (whetherToHideAdvancedOptions == JOptionPane.NO_OPTION) {
        configuration.setHideAdvancedOptions(false);
    }

    // Ask if they want to scan shared folders
    int whetherToScanSharedFolders = JOptionPane.showOptionDialog(null,
            Messages.getString("Wizard.IsStartupScan"), String.format(status, currentQuestionNumber++),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[0]);

    if (whetherToScanSharedFolders == JOptionPane.YES_OPTION) {
        configuration.setScanSharedFoldersOnStartup(true);
    } else if (whetherToScanSharedFolders == JOptionPane.NO_OPTION) {
        configuration.setScanSharedFoldersOnStartup(false);
    }

    // Ask to set at least one shared folder
    JOptionPane.showOptionDialog(null, Messages.getString("Wizard.12"),
            String.format(status, currentQuestionNumber++), JOptionPane.OK_OPTION,
            JOptionPane.INFORMATION_MESSAGE, null, okOptions, okOptions[0]);

    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                JFileChooser chooser;
                try {
                    chooser = new JFileChooser();
                } catch (Exception ee) {
                    chooser = new JFileChooser(new RestrictedFileSystemView());
                }

                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                chooser.setDialogTitle(Messages.getString("Wizard.12"));
                chooser.setMultiSelectionEnabled(false);
                if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                    configuration.setOnlySharedDirectory(chooser.getSelectedFile().getAbsolutePath());
                } else {
                    // If the user cancels this option, the default directories will be used.
                }
            }
        });
    } catch (InterruptedException | InvocationTargetException e) {
        LOGGER.error("Error when saving folders: ", e);
    }

    // The wizard finished, do not ask them again
    configuration.setRunWizard(false);

    // Save all changes
    try {
        configuration.save();
    } catch (ConfigurationException e) {
        LOGGER.error("Error when saving changed configuration: ", e);
    }
}