Example usage for javax.swing SwingUtilities isEventDispatchThread

List of usage examples for javax.swing SwingUtilities isEventDispatchThread

Introduction

In this page you can find the example usage for javax.swing SwingUtilities isEventDispatchThread.

Prototype

public static boolean isEventDispatchThread() 

Source Link

Document

Returns true if the current thread is an AWT event dispatching thread.

Usage

From source file:com.jidesoft.spring.richclient.docking.view.JideAbstractView.java

/**
 * Activates this view taking care of EDT issues
 *
 *//*from ww  w .j  a  va2  s.co  m*/
public void activateView() {
    if (SwingUtilities.isEventDispatchThread()) {
        getActiveWindow().getPage().showView(getId());
    } else {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                getActiveWindow().getPage().showView(getId());
            }

        });
    }
}

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 ww  w  .j a  v  a  2  s.  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:Main.java

/**
 * Fires a {@link ActionListener}. This is useful for firing 
 * {@link ApplicationAction}s to show blocking dialog. This can be called
 * on and off the EDT./*  w  w w.  ja v a  2 s. c om*/
 *
 * @param listener the listener to fire.
 * @param evt the action event to fire.
 * @param modifiers the modifier keys held down during this action.
 * @see ActionEvent#ActionEvent(Object, int, String, long, int)
 */
public static void fireAction(final ActionListener listener, final ActionEvent evt) {
    if (!SwingUtilities.isEventDispatchThread()) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                fireAction(listener, evt);
            }
        });
        return;
    }
    listener.actionPerformed(evt);
}

From source file:SafeRepaint.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    System.out.println(SwingUtilities.isEventDispatchThread());
}

From source file:org.nbheaven.sqe.codedefects.dashboard.controlcenter.panels.Statistics.java

private void updateView() {
    if (!SwingUtilities.isEventDispatchThread()) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                updateView();//from w ww  .j  a  v  a 2  s.  com
            }
        });
        return;
    }

    assert SwingUtilities.isEventDispatchThread();

    // Update per project view first
    perProjectDataSet.clear();
    for (QualityProvider qualityProvider : SQEUtilities.getProviders()) {
        String providerName = qualityProvider.getDisplayName();
        perProjectDataSet.addValue(0, CodeDefectSeverity.ERROR, providerName);
        perProjectDataSet.addValue(0, CodeDefectSeverity.WARNING, providerName);
        perProjectDataSet.addValue(0, CodeDefectSeverity.INFO, providerName);
    }

    if (null != activeProject) {
        Collection<? extends QualitySession> sessions = activeProject.getLookup()
                .lookupAll(QualitySession.class);
        for (QualitySession session : sessions) {
            if (null == session.getResult()) {
                continue;
            }
            QualityResultStatistic statistic = session.getResult().getLookup()
                    .lookup(QualityResultStatistic.class);
            if (null != statistic) {
                String providerName = session.getProvider().getDisplayName();
                perProjectDataSet.addValue(statistic.getCodeDefectCount(CodeDefectSeverity.ERROR),
                        CodeDefectSeverity.ERROR, providerName);
                perProjectDataSet.addValue(statistic.getCodeDefectCount(CodeDefectSeverity.WARNING),
                        CodeDefectSeverity.WARNING, providerName);
                perProjectDataSet.addValue(statistic.getCodeDefectCount(CodeDefectSeverity.INFO),
                        CodeDefectSeverity.INFO, providerName);
            }
        }
    }
    Statistics.this.invalidate();
    Statistics.this.revalidate();
    Statistics.this.repaint();
}

From source file:com.otway.picasasync.syncutil.SyncManager.java

public void BeginCompleteSync() {

    if (syncState.getIsInProgress()) {

        log.warn("Sync started when already in progress. Doing nothing...");
        return;/*  ww  w . j ava2 s  .com*/
    }

    LocalDateTime startDate = LocalDateTime.now();
    startDate = startDate.plusDays(-1 * settings.getSyncDateRange());
    boolean endedWithError = true;

    log.info("Synchronisation started. Max photo age: " + startDate);

    if (SwingUtilities.isEventDispatchThread()) {
        log.error("Sync started on GUI thread!");
        throw new RuntimeException("This method should not be run on the GUI thread");
    }

    try {
        syncState.start();

        File rootFolder = initFolder();

        syncState.setStatus("Starting synchronisation");

        // Do the actual sync
        Synchronise(rootFolder, startDate);

        syncState.setStatus("Sync complete");

        endedWithError = false;

    } catch (ServiceForbiddenException forbiddenEx) {

        log.error("Auth expired. Discarding web client; will re-auth on next loop.");
        invalidateWebClient();
    } catch (UnknownHostException ex) {
        log.warn("Unknown host exception. Did we lose internet access?");
        // Cancel this sync, and we'll try again in a bit
        syncState.setStatus("Error finding Google.com. Sync Aborted.");
    } catch (SocketException ex) {
        log.warn("Socket exception. Did we lose internet access?");
        // Cancel this sync, and we'll try again in a bit
        syncState.setStatus("Connection error. Sync Aborted.");
    } catch (SocketTimeoutException ex) {
        log.warn("Socket timeout. Did we lose internet access?");
        // Cancel this sync, and we'll try again in a bit
        syncState.setStatus("Connection timeout. Sync aborted.");
    } catch (Exception ex) {
        log.error("Unexpected error: ", ex);
    } finally {
        log.info("Synchronisation ended.");
        if (endedWithError)
            syncState.setStatus("Sync failed.");
        syncState.cancel(endedWithError);
    }
}

From source file:javazoom.jlgui.player.amp.equalizer.ui.EqualizerUI.java

public void loadUI() {
    log.info("Load EqualizerUI (EDT=" + SwingUtilities.isEventDispatchThread() + ")");
    removeAll();/* w w w . j a  v  a2s . co m*/
    // Background
    ImageBorder border = new ImageBorder();
    border.setImage(ui.getEqualizerImage());
    setBorder(border);
    // On/Off
    add(ui.getAcEqOnOff(), ui.getAcEqOnOff().getConstraints());
    ui.getAcEqOnOff().removeActionListener(this);
    ui.getAcEqOnOff().addActionListener(this);
    // Auto
    add(ui.getAcEqAuto(), ui.getAcEqAuto().getConstraints());
    ui.getAcEqAuto().removeActionListener(this);
    ui.getAcEqAuto().addActionListener(this);
    // Sliders
    add(ui.getAcEqPresets(), ui.getAcEqPresets().getConstraints());
    for (int i = 0; i < ui.getAcEqSliders().length; i++) {
        add(ui.getAcEqSliders()[i], ui.getAcEqSliders()[i].getConstraints());
        ui.getAcEqSliders()[i].setValue(maxGain - gainValue[i]);
        ui.getAcEqSliders()[i].removeChangeListener(this);
        ui.getAcEqSliders()[i].addChangeListener(this);
    }
    if (ui.getSpline() != null) {
        ui.getSpline().setValues(gainValue);
        add(ui.getSpline(), ui.getSpline().getConstraints());
    }
    // Popup menu on TitleBar
    mainpopup = new JPopupMenu();
    String[] presets = { "Normal", "Classical", "Club", "Dance", "Full Bass", "Full Bass & Treble",
            "Full Treble", "Laptop", "Live", "Party", "Pop", "Reggae", "Rock", "Techno" };
    JMenuItem mi;
    for (int p = 0; p < presets.length; p++) {
        mi = new JMenuItem(presets[p]);
        mi.removeActionListener(this);
        mi.addActionListener(this);
        mainpopup.add(mi);
    }
    ui.getAcEqPresets().removeActionListener(this);
    ui.getAcEqPresets().addActionListener(this);
    validate();
}

From source file:com.kenai.redminenb.query.RedmineQuery.java

private boolean doRefresh(final boolean autoRefresh) {
    // XXX what if already running! - cancel task
    assert !SwingUtilities.isEventDispatchThread() : "Accessing remote host. Do not call in awt"; // NOI18N

    final boolean ret[] = new boolean[1];
    executeQuery(new Runnable() {
        @Override/*from   w w  w .j av a  2s .  c  om*/
        public void run() {
            Redmine.LOG.log(Level.FINE, "refresh start - {0}", name); // NOI18N
            try {
                if (delegateContainer != null) {
                    delegateContainer.refreshingStarted();
                }
                // keeps all issues we will retrieve from the server
                // - those matching the query criteria
                // - and the obsolete ones
                Set<RedmineIssue> queryIssues = new HashSet<>();

                issues.clear();
                //                    archivedIssues.clear();
                if (isSaved()) {
                    // read the stored state ...
                    //                  queryIssues.addAll(repository.getIssueCache().readQueryIssues(getStoredQueryName()));
                    //                 queryIssues.addAll(repository.getIssueCache().readArchivedQueryIssues(getStoredQueryName()));
                    // ... and they might be rendered obsolete if not returned by the query
                    //                        archivedIssues.addAll(queryIssues);
                }
                firstRun = false;
                try {
                    List<com.taskadapter.redmineapi.bean.Issue> issueArr = doSearch(
                            queryController.getSearchParameters());
                    for (com.taskadapter.redmineapi.bean.Issue issue : issueArr) {
                        getController().addProgressUnit(RedmineIssue.getDisplayName(issue));
                        RedmineIssue redmineIssue = new RedmineIssue(repository, issue);
                        issues.add(redmineIssue);
                        if (delegateContainer != null) {
                            delegateContainer.add(redmineIssue);
                        }
                        fireNotifyData(redmineIssue); // XXX - !!! triggers getIssues()
                    }

                } catch (Exception e) {
                    Exceptions.printStackTrace(e);
                }

                // only issues not returned by the query are obsolete
                //archivedIssues.removeAll(issues);
                if (isSaved()) {
                    // ... and store all issues you got
                    //                  repository.getIssueCache().storeQueryIssues(getStoredQueryName(), issues.toArray(new String[issues.size()]));
                    //repository.getIssueCache().storeArchivedQueryIssues(getStoredQueryName(), archivedIssues.toArray(new String[0]));
                }

                // now get the task data for
                // - all issue returned by the query
                // - and issues which were returned by some previous run and are archived now
                queryIssues.addAll(issues);
                if (delegateContainer != null) {
                    delegateContainer.refreshingFinished();
                }
                getController().switchToDeterminateProgress(queryIssues.size());

            } finally {
                logQueryEvent(issues.size(), autoRefresh);
                Redmine.LOG.log(Level.FINE, "refresh finish - {0}", name); // NOI18N
            }
        }
    });

    return ret[0];
}

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

/**
 * Set the value of the bean to the JComponent
 *///from   w w w  .jav a 2  s .  com
public final void setValueToJComponent() {
    if (SwingUtilities.isEventDispatchThread()) {
        setValueToJComponentInternal();
    } else {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    setValueToJComponentInternal();
                }
            });
        } catch (Throwable e) {
            e.printStackTrace();
            throw new AWSystemException("Problems setting values to jcompoent:" + fieldName, e);
        }
    }

}

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

/**
 * Show a message dialog using//from  www .  ja  va2  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);
        }
    }
}