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:net.java.sip.communicator.impl.gui.main.chat.ChatConversationPanel.java

/**
 * Sets the given document to the editor pane in this panel.
 *
 * @param document the document to set/*from ww w.j  a  v  a 2 s . co m*/
 */
public void setContent(final HTMLDocument document) {
    if (!SwingUtilities.isEventDispatchThread()) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                setContent(document);
            }
        });
        return;
    }

    synchronized (scrollToBottomRunnable) {
        scrollToBottomIsPending = true;

        this.document = document;
        chatTextPane.setDocument(this.document);
    }
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

public final void testPublishAndProcess() throws Exception {
    final Exchanger<List<Integer>> listExchanger = 
        new Exchanger<List<Integer>>();
    final Exchanger<Boolean> boolExchanger = 
        new Exchanger<Boolean>();
    SwingWorker<List<Integer>,Integer> test = 
        new SwingWorker<List<Integer>, Integer>() {
            List<Integer> receivedArgs = 
                Collections.synchronizedList(new ArrayList<Integer>());
            Boolean isOnEDT = Boolean.TRUE;
            final int NUMBERS = 100;
            @Override//from  w w w. j  av a2  s  .c  o m
            protected List<Integer> doInBackground() throws Exception {
                List<Integer> ret = 
                    Collections.synchronizedList(
                        new ArrayList<Integer>(NUMBERS));
                for (int i = 0; i < NUMBERS; i++) {
                    publish(i);
                    ret.add(i);
                }
                return ret;
            }
            @Override
            protected void process(List<Integer> args) {
                for(Integer i : args) {
                    receivedArgs.add(i);
                }
                isOnEDT = isOnEDT && SwingUtilities.isEventDispatchThread();
                if (receivedArgs.size() == NUMBERS) {
                    try {
                        boolExchanger.exchange(isOnEDT);
                        listExchanger.exchange(receivedArgs);
                    } catch (InterruptedException ignore) {
                        ignore.printStackTrace();
                    }
                }
            }
    };
    test.execute();
    assertTrue(boolExchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT));
    assertEquals(test.get(TIME_OUT, TIME_OUT_UNIT), 
        listExchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT));
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

public final void testDone() throws Exception {
    final String testString  = "test"; 
    final Exchanger<Boolean> exchanger = new Exchanger<Boolean>();
    SwingWorker<?,?> test = new SwingWorker<String, Object>() {
        @Override/*from   www .ja v a2s.c  o  m*/
        protected String doInBackground() throws Exception {
            return testString;
        }
        @Override
        protected void done() {
            try {
                exchanger.exchange(
                    testString == get()
                    && SwingUtilities.isEventDispatchThread());
            } catch (Exception ignore) {
            }
        }
    };
    test.execute();
    assertTrue(exchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT));
}

From source file:de.huxhorn.lilith.swing.MainFrame.java

public Colors getColors(EventWrapper eventWrapper) {
    if (!SwingUtilities.isEventDispatchThread()) {
        if (logger.isErrorEnabled())
            logger.error("Not on EventDispatchThread!");
    }//from  w w  w.j  a  v a 2 s .  co m

    ColorScheme result = null;
    if (activeConditions != null) {
        for (SavedCondition current : activeConditions) {
            Condition condition = current.getCondition();
            if (condition != null && condition.isTrue(eventWrapper)) {
                if (result == null) {
                    result = current.getColorScheme();
                    if (result != null) {
                        try {
                            result = result.clone();
                        } catch (CloneNotSupportedException e) {
                            if (logger.isErrorEnabled())
                                logger.error("Exception while cloning ColorScheme!!", e);
                        }
                    }
                } else {
                    result.mergeWith(current.getColorScheme());
                }

            }
            if (result != null && result.isAbsolute()) {
                return new Colors(result, false);
            }
        }
    }

    if (coloringWholeRow) {
        Object eventObj = eventWrapper.getEvent();
        if (eventObj instanceof LoggingEvent) {
            Colors c = getColors(((LoggingEvent) eventObj).getLevel());
            if (result != null) {
                return new Colors(result.mergeWith(c.getColorScheme()), false);
            }
            return c;
        }
        if (eventObj instanceof AccessEvent) {
            Colors c = getColors(HttpStatus.getType(((AccessEvent) eventObj).getStatusCode()));
            if (result != null) {
                return new Colors(result.mergeWith(c.getColorScheme()), false);
            }
            return c;
        }
    }

    // return the previously found ColorScheme even though it's not absolute
    if (result != null) {
        return new Colors(result, false);
    }
    return null;
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

public final void testPropertyChange() throws Exception {
    final Exchanger<Boolean> boolExchanger = 
        new Exchanger<Boolean>();
    final SwingWorker<?,?> test = 
        new SwingWorker<Object, Object>() {
            @Override//from  w w  w .  j ava 2 s . co m
            protected Object doInBackground() throws Exception {
                firePropertyChange("test", null, "test");
                return null;
            }
        };
    test.addPropertyChangeListener(
        new PropertyChangeListener() {
            boolean isOnEDT = true;

            public  void propertyChange(PropertyChangeEvent evt) {
                isOnEDT &= SwingUtilities.isEventDispatchThread();
                if ("state".equals(evt.getPropertyName())
                    && StateValue.DONE == evt.getNewValue()) {
                    try {
                        boolExchanger.exchange(isOnEDT);
                    } catch (Exception ignore) {
                        ignore.printStackTrace();
                    }
                }
            }
        });
    test.execute();
    assertTrue(boolExchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT));
}

From source file:com.archivas.clienttools.arcmover.gui.panels.ProfilePanel.java

protected void openSelectedFile() {
    if (!SwingUtilities.isEventDispatchThread()) {
        String errMsg = "openSelectedFile is not on the EDT but it should be";
        IllegalStateException ex = new IllegalStateException(errMsg);
        LOG.log(Level.SEVERE, errMsg, ex);
        throw ex;
    }//w w  w.j a va2  s  .  c  o  m
    try {
        if (selectedFile != null) {
            // check if this item is a directory
            if (selectedFile.isDirectory()) {
                ArcMoverDirectory newDir = (ArcMoverDirectory) selectedFile;
                if (!newDir.canRead()) {
                    GUIHelper.showMessageDialog(this,
                            "An error occurred reading directory "
                                    + profileModel.getSelectedProfile().decode(newDir.getPath()),
                            "Error Reading Directory", JOptionPane.ERROR_MESSAGE);
                } else {
                    setPathAndFileListToDirectory(newDir.getPath());
                }
            } else if (selectedFile.isSymlink()) {
                // do nothing
            } else if (!selectedFile.getParent().isVersionList()
                    && profileModel.getSelectedProfile().supportsVersioning()) {
                // This is file with versions, and we're not in the version list.
                setPathAndFileListToDirectory(versionPath(selectedFile));
            } else {
                openSelectedRow();
            }
        }
    } catch (Exception e) {
        String msg = "Unexpected error";
        LOG.log(Level.WARNING, msg, e);
        JOptionPane.showMessageDialog(this, msg, "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatPanel.java

/**
 * Sends the given file through the currently selected chat transport.
 *
 * @param file the file to send/* w  w w .  ja v  a  2 s .  c  o  m*/
 */
public void sendFile(final File file) {
    // We need to be sure that the following code is executed in the event
    // dispatch thread.
    if (!SwingUtilities.isEventDispatchThread()) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                sendFile(file);
            }
        });
        return;
    }

    final ChatTransport fileTransferTransport = findFileTransferChatTransport();

    // If there's no operation set we show some "not supported" messages
    // and we return.
    if (fileTransferTransport == null) {
        logger.error("Failed to send file.");

        this.addErrorMessage(chatSession.getChatName(),
                GuiActivator.getResources().getI18NString("service.gui.FILE_SEND_FAILED",
                        new String[] { file.getName() }),
                GuiActivator.getResources().getI18NString("service.gui.FILE_TRANSFER_NOT_SUPPORTED"));

        return;
    }

    final SendFileConversationComponent fileComponent = new SendFileConversationComponent(this,
            fileTransferTransport.getDisplayName(), file);

    if (ConfigurationUtils.isHistoryShown() && !isHistoryLoaded) {
        synchronized (incomingEventBuffer) {
            incomingEventBuffer.add(fileComponent);
        }
    } else
        getChatConversationPanel().addComponent(fileComponent);

    this.sendFile(file, fileComponent);
}

From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java

/**
 * /*w w w . j ava2 s  .  c  o m*/
 */
protected void setupUI(final boolean isPostSave) throws QueryTask.QueryBuilderContextException {
    if (!isHeadless && !SwingUtilities.isEventDispatchThread()) {
        throw new RuntimeException("Method called from invalid thread.");
    }

    queryFieldsPanel.removeAll();
    queryFieldItems.clear();
    queryFieldsPanel.validate();
    columnDefStr = null;
    tableList.clearSelection();
    contextPanel.setVisible(query == null);
    tableList.setSelectedIndex(-1);
    if (query != null) {
        //query.forceLoad(true); 
        Short tblId = query.getContextTableId();
        if (tblId != null) {
            for (int i = 0; i < tableList.getModel().getSize(); i++) {
                TableQRI qri = (TableQRI) tableList.getModel().getElementAt(i);
                if (qri.getTableInfo().getTableId() == tblId.intValue()) {
                    tableList.setSelectedIndex(i);
                    break;
                }
            }
        }
    }

    List<QueryFieldPanel> qfps = null;
    boolean dirty = false;
    List<String> missingFlds = new LinkedList<String>();
    boolean doAutoMap = query == null || query.getId() == null;
    if (query != null) {
        TableQRI qri = (TableQRI) tableList.getSelectedValue();
        if (qri == null) {
            //throw new RuntimeException("Invalid context for query."); 
            throw ((QueryTask) task).new QueryBuilderContextException();
        }
        //query.forceLoad(true);                   
        qfps = !isExportMapping
                ? getQueryFieldPanels(this, query.getFields(), tableTree, tableTreeHash, saveBtn, missingFlds)
                : getQueryFieldPanelsForMapping(this, query.getFields(), tableTree, tableTreeHash, saveBtn,
                        schemaMapping, missingFlds,
                        (doAutoMap ? ConceptMapUtils.getDefaultDarwinCoreMappings() : null));
        if (missingFlds.size() > 0) {
            JList list = new JList(new Vector<String>(missingFlds));
            CellConstraints cc = new CellConstraints();
            PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p:g,2px,f:p:g"));
            pb.add(UIHelper.createI18NLabel("QB_FIELDS_NOT_ADDED"), cc.xy(1, 1));
            pb.add(UIHelper.createScrollPane(list), cc.xy(1, 3));
            pb.setDefaultDialogBorder();

            dirty = qfps.size() > 0;
            CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getTopWindow(),
                    UIRegistry.getResourceString("QB_FIELD_MISSING_TITLE"), true, CustomDialog.OK_BTN,
                    pb.getPanel());
            dlg.setOkLabel(UIRegistry.getResourceString("CLOSE"));
            dlg.setVisible(true);
        }
    }

    boolean header = true;
    for (final QueryFieldPanel qfp : qfps) {
        if (header) {
            header = false;
            this.queryFieldsScroll.setColumnHeaderView(qfp);
        } else {
            queryFieldItems.add(qfp);
            qfp.addMouseListener(new MouseInputAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    selectQFP(qfp);
                }
            });
            qfp.resetValidator();
            queryFieldsPanel.add(qfp);
            //doAutoMap &= qfp.getFieldQRI() == null;
        }
    }
    qualifyFieldLabels();

    for (QueryFieldPanel qfp : queryFieldItems) {
        if (qfp.isAutoMapped()) {
            SpQueryField qf = new SpQueryField();
            qf.initialize();
            qf.setFieldName(qfp.getFieldQRI().getFieldName());
            qf.setStringId(qfp.getFieldQRI().getStringId());
            qfp.setQueryFieldForAutomapping(qf);
            query.addReference(qf, "fields");
            addNewMapping(qfp.getFieldQRI(), qf, qfp, false);
            dirty = true;
            qfp.setAutoMapped(false);
        }
    }

    /*if (doAutoMap)
    {
       for (QueryFieldPanel qfp : queryFieldItems)
       {
      if (!qfp.isConditionForSchema())
    {
       Vector<MappedFieldInfo> mappedTos = ConceptMapUtils.getDefaultDarwinCoreMappings().get(qfp.getSchemaItem().getFieldName().toLowerCase());
               
       if (mappedTos != null)
       {
          for (MappedFieldInfo mappedTo : mappedTos)
          {
             FieldQRI fqri = getFieldQRI(tableTree, mappedTo
                .getFieldName(), mappedTo.isRel(), mappedTo
                .getStringId(), getTableIds(mappedTo
                .getTableIds()), 0, tableTreeHash);
             if (fqri != null)
             {
                SpQueryField qf = new SpQueryField();
                qf.initialize();
                qf.setFieldName(fqri.getFieldName());
                qf.setStringId(fqri.getStringId());
                query.addReference(qf, "fields");
                addNewMapping(fqri, qf, qfp);
                dirty = true;
                break;
             }
          }
       }
    }
       }
    }*/

    fillNextList(tableList);

    updateAvailableConcepts();

    SwingUtilities.invokeLater(new Runnable() {

        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {
            distinctChk.setSelected(query.isSelectDistinct());
            countOnlyChk.setSelected(query.getCountOnly() == null ? false : query.getCountOnly());
            countOnly = countOnlyChk.isSelected();
            searchSynonymyChk.setSelected(
                    query.getSearchSynonymy() == null ? searchSynonymy : query.getSearchSynonymy());
            searchSynonymy = searchSynonymyChk.isSelected();
            smushedChk.setSelected(query.getSmushed() == null ? smushed : query.getSmushed());
            smushed = smushedChk.isSelected();
        }

    });
    final boolean saveBtnEnabled = dirty;
    if (!isHeadless) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                adjustPanelUI(saveBtnEnabled, isPostSave);
            }
        });
    } else {
        adjustPanelUI(saveBtnEnabled, isPostSave);
    }
}

From source file:de.cismet.verdis.CidsAppBackend.java

/**
 * DOCUMENT ME!//  w  w  w  .j av  a 2s. c om
 *
 * @param  title      DOCUMENT ME!
 * @param  message    DOCUMENT ME!
 * @param  exception  DOCUMENT ME!
 */
public void showError(final String title, final String message, final Exception exception) {
    if (SwingUtilities.isEventDispatchThread()) {
        final ErrorInfo errorInfo = new ErrorInfo(title, message, null, "", exception, null, null);
        JXErrorPane.showDialog(Main.getInstance(), errorInfo);
    } else {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    showError(title, message, exception);
                }
            });
        } catch (final Exception ex) {
            LOG.error(ex, ex);
        }
    }
}

From source file:com.igormaznitsa.mindmap.swing.panel.MindMapPanel.java

@Override
public void revalidate() {
    final Runnable runnable = new Runnable() {
        @Override/*from  w w w. j a va2 s  . c om*/
        public void run() {
            if (!isValid()) {
                final Graphics2D gfx = (Graphics2D) getGraphics();
                if (gfx != null && calculateElementSizes(gfx, model, config)) {
                    changeSizeOfComponentWithNotification(
                            layoutFullDiagramWithCenteringToPaper(gfx, model, config, getSize()));
                }
            }
        }
    };
    if (SwingUtilities.isEventDispatchThread()) {
        runnable.run();
    } else {
        SwingUtilities.invokeLater(runnable);
    }
}