Java Code Examples for java.awt.EventQueue

The following examples show how to use java.awt.EventQueue. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@SuppressWarnings("unchecked")
public EventQueueDelegateFromMap(Map<String, Map<String, Object>> objectMap) {
    Map<String, Object> methodMap = objectMap.get("afterDispatch");
    afterDispatchEventArgument = (AWTEvent[]) methodMap.get("event");
    afterDispatchHandleArgument = (Object[]) methodMap.get("handle");
    afterDispatchCallable = (Callable<Void>) methodMap.get("method");

    methodMap = objectMap.get("beforeDispatch");
    beforeDispatchEventArgument = (AWTEvent[]) methodMap.get("event");
    beforeDispatchCallable = (Callable<Object>) methodMap.get("method");

    methodMap = objectMap.get("getNextEvent");
    getNextEventEventQueueArgument =
        (EventQueue[]) methodMap.get("eventQueue");
    getNextEventCallable = (Callable<AWTEvent>) methodMap.get("method");
}
 
Example 2
Source Project: netbeans   Source File: RevertPanel.java    License: Apache License 2.0 6 votes vote down vote up
void setRootNode(final TreeNode root) {
    if(root != null) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                tree.setModel(new DefaultTreeModel(root));
                for (int i = 0; i < tree.getRowCount(); i++) {
                    tree.expandRow(i);
                }
                listScrollPane.setVisible(true);
                titleLabel.setVisible(true);
                initPanel.setVisible(false);
            }
        });
    } else {
        messageLabel.setText(NbBundle.getMessage(RevertDeletedAction.class, "MSG_NO_FILES")); // NOI18N
    }
}
 
Example 3
Source Project: Pixelitor   Source File: PreferencesPanel.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void addLanguageChooser(GridBagHelper gbh) {
    var languages = new EnumComboBoxModel<>(Language.class);
    languages.setSelectedItem(Texts.getCurrentLanguage());

    @SuppressWarnings("unchecked")
    JComboBox<Language> langChooser = new JComboBox<>(languages);

    langChooser.setName("langChooser");
    gbh.addLabelAndControl("Language: ", langChooser);
    langChooser.addActionListener(e -> {
        Language language = languages.getSelectedItem();
        if (language != Texts.getCurrentLanguage()) {
            Texts.setCurrentLang(language);
            EventQueue.invokeLater(() -> Dialogs.showInfoDialog(this,
                "Needs Restart",
                "Changing the display language will take effect after restarting Pixelitor."));
        }
    });
}
 
Example 4
Source Project: FlatLaf   Source File: FlatLaf.java    License: Apache License 2.0 6 votes vote down vote up
private static void reSetLookAndFeel() {
	EventQueue.invokeLater( () -> {
		LookAndFeel lookAndFeel = UIManager.getLookAndFeel();
		try {
			// re-set current LaF
			UIManager.setLookAndFeel( lookAndFeel );

			// must fire property change events ourself because old and new LaF are the same
			PropertyChangeEvent e = new PropertyChangeEvent( UIManager.class, "lookAndFeel", lookAndFeel, lookAndFeel );
			for( PropertyChangeListener l : UIManager.getPropertyChangeListeners() )
				l.propertyChange( e );

			// update UI
			updateUI();
		} catch( UnsupportedLookAndFeelException ex ) {
			LOG.log( Level.SEVERE, "FlatLaf: Failed to reinitialize look and feel '" + lookAndFeel.getClass().getName() + "'.", ex );
		}
	} );
}
 
Example 5
Source Project: FlatLaf   Source File: FlatLaf.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Update UI of all application windows later.
 */
public static void updateUILater() {
	synchronized( FlatLaf.class ) {
		if( updateUIPending )
			return;

		updateUIPending = true;
	}

	EventQueue.invokeLater( () -> {
		updateUI();
		synchronized( FlatLaf.class ) {
			updateUIPending = false;
		}
	} );
}
 
Example 6
Source Project: netbeans   Source File: RemoteStyleSheetCache.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Closes the given collection of files.
 * 
 * @param files files to close.
 */
private static void closeFiles(final Collection<FileObject> files) {
    if (EventQueue.isDispatchThread()) {
        for (FileObject file : files) {
            try {
                DataObject dob = DataObject.find(file);
                Closable close = dob.getLookup().lookup(Closable.class);
                if (close != null) {
                    close.close();
                }
            } catch (DataObjectNotFoundException dnfex) {
                Logger.getLogger(RemoteStyleSheetCache.class.getName()).log(Level.INFO, null, dnfex);
            }
        }
    } else {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                closeFiles(files);
            }
        });
    }
}
 
Example 7
Source Project: netbeans   Source File: HTMLDialogImpl.java    License: Apache License 2.0 6 votes vote down vote up
public String showAndWait() {
    if (EventQueue.isDispatchThread()) {
        run();
        showDialog();
    } else {
        if (HtmlToolkit.getDefault().isApplicationThread()) {
            nestedLoop = true;
            EventQueue.invokeLater(this);
            HtmlToolkit.getDefault().enterNestedLoop(this);
        } else {
            try {
                EventQueue.invokeAndWait(this);
            } catch (InterruptedException | InvocationTargetException ex) {
                throw new IllegalStateException(ex);
            }
            showDialog();
        }
    }
    Object val = dd.getValue();
    return val instanceof JButton ? ((JButton)val).getName() : null;
}
 
Example 8
Source Project: netbeans   Source File: StatusTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testIgnoredBySharabilityAWT () throws Throwable {
    final Throwable[] th = new Throwable[1];
    Future<Project[]> projectOpenTask = OpenProjects.getDefault().openProjects();
    if (!projectOpenTask.isDone()) {
        try {
            projectOpenTask.get();
        } catch (Exception ex) {
            // not interested
        }
    }
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            try {
                skeletonIgnoredBySharability();
            } catch (Throwable t) {
                th[0] = t;
            }
        }
    });
    if (th[0] != null) {
        throw th[0];
    }
}
 
Example 9
Source Project: jdk8u-dev-jdk   Source File: X11InputMethod.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Flushes composed and committed text held in this context.
 * This method is invoked in the AWT Toolkit (X event loop) thread context
 * and thus inside the AWT Lock.
 */
// NOTE: This method may be called by privileged threads.
//       This functionality is implemented in a package-private method
//       to insure that it cannot be overridden by client subclasses.
//       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
void flushText() {
    String flush = (committedText != null ? committedText : "");
    if (composedText != null) {
        flush += composedText.toString();
    }

    if (!flush.equals("")) {
        AttributedString attrstr = new AttributedString(flush);
        postInputMethodEvent(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
                             attrstr.getIterator(),
                             flush.length(),
                             null,
                             null,
                             EventQueue.getMostRecentEventTime());
        composedText = null;
        committedText = null;
    }
}
 
Example 10
Source Project: netbeans   Source File: AnnotationBar.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Runs the given runnable after the previous revision is determined
 * @param runnable
 */
private void runWithRevision (final Runnable runnable, final boolean inAWT) {
    if (revisionPerLine != null) {
        // getting the prevoius revision may take some time, running in bg
        new HgProgressSupport() {
            @Override
            protected void perform() {
                previousRevision = getParentRevision(file, revisionPerLine);
                if (!isCanceled() && previousRevision != null) {
                    originalFile = AnnotationBar.this.getOriginalFile(file, revisionPerLine);
                    if (!isCanceled() && file != null) {
                        if (inAWT) {
                            EventQueue.invokeLater(runnable);
                        } else {
                            getRequestProcessor().post(runnable);
                        }
                    }
                }
            }
        }.start(Mercurial.getInstance().getRequestProcessor(), repositoryRoot,
                NbBundle.getMessage(AnnotationBar.class, "MSG_GettingPreviousRevision")); //NOI18N
    }
}
 
Example 11
Source Project: netbeans   Source File: TopLoggingAWTTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testAWTErrorReported() throws Exception {
    TopLogging.initialize();
    MockServices.setServices(MyHandler.class);
    
    final IllegalStateException ex = new IllegalStateException("I am broken");
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            throw ex;
        }
    });
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
        }
    });
    assertEquals("Exception provided", ex, getPublished().getThrown());
    assertNotNull("Our handler called", uncaught);
}
 
Example 12
Source Project: netbeans   Source File: RepositoryBrowserPanel.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Node[] createNodes (BranchNodeType key) {
    final BranchesNode node;
    switch (key) {
        case LOCAL:
            node = local = new BranchesNode(repository, key, branches);
            break;
        case REMOTE:
            node = remote = new BranchesNode(repository, key, branches);
            break;
        default:
            throw new IllegalStateException();
    }
    if (options.contains(Option.EXPAND_BRANCHES)) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run () {
                tree.expandNode(node);
            }
        });
    }
    return new Node[] { node };
}
 
Example 13
Source Project: netbeans   Source File: HgVersioningTopComponent.java    License: Apache License 2.0 6 votes vote down vote up
void refreshBranchName () {
    Runnable runnable = new Runnable () {
        @Override
        public void run() {
            if (info != null) {
                info.removePropertyChangeListener(HgVersioningTopComponent.this);
                info = null;
            }
            Set<File> repositoryRoots = HgUtils.getRepositoryRoots(context);
            String label = null;
            if (repositoryRoots.size() == 1) {
                info = WorkingCopyInfo.getInstance(repositoryRoots.iterator().next());
                info.addPropertyChangeListener(HgVersioningTopComponent.this);
                label = info.getCurrentBranch();
            }
            setBranchTitle(label);
        }
    };
    if (EventQueue.isDispatchThread()) {
        Utils.post(runnable);
    } else {
        runnable.run();
    }
}
 
Example 14
@Override
public void setSelectedItem(final Object anItem) {
    if (anItem == null) {
        return;
    }
    // need to do that in the RP since fetch can be running
    RP.post(new Runnable() {
        @Override
        public void run() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    String standard = (String) anItem;
                    if (!standard.equals(selectedStandard)
                            && standards.contains(standard)) {
                        selectedStandard = standard;
                        fireContentsChanged();
                    }
                }
            });
        }
    });
}
 
Example 15
public void testIteratorCreatesUI() throws Exception {
    assertFalse("No EDT", EventQueue.isDispatchThread());
    
    FileObject fo = FileUtil.getConfigFile("smpl.tmp");
    assertNotNull("layer file found", fo);
    final FeatureOnDemandWizardIterator it = new FeatureOnDemandWizardIterator(fo);
    fo.setAttribute("instantiatingIterator", it);
    
    final TemplateWizard tw = new TemplateWizard();
    tw.setTemplate(DataObject.find(fo));
    
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            assertNotNull("Panel found", it.current());
            assertComponent("Our component found", it.current().getComponent(), tw);
        }
    });
}
 
Example 16
/**
 * Flushes composed and committed text held in this context.
 * This method is invoked in the AWT Toolkit (X event loop) thread context
 * and thus inside the AWT Lock.
 */
// NOTE: This method may be called by privileged threads.
//       This functionality is implemented in a package-private method
//       to insure that it cannot be overridden by client subclasses.
//       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
void flushText() {
    String flush = (committedText != null ? committedText : "");
    if (composedText != null) {
        flush += composedText.toString();
    }

    if (!flush.equals("")) {
        AttributedString attrstr = new AttributedString(flush);
        postInputMethodEvent(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
                             attrstr.getIterator(),
                             flush.length(),
                             null,
                             null,
                             EventQueue.getMostRecentEventTime());
        composedText = null;
        committedText = null;
    }
}
 
Example 17
Source Project: Ardulink-1   Source File: SimpleSmartCarDriver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Launch the application.
 */
public static void main(String[] args) {
	EventQueue.invokeLater(new Runnable() {
		public void run() {
			try {
				for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
					if ("Nimbus".equals(laf.getName())) {
						UIManager.setLookAndFeel(laf.getClassName());
					}
				}
				SimpleSmartCarDriver frame = new SimpleSmartCarDriver();
				frame.setVisible(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	});
}
 
Example 18
Source Project: netbeans   Source File: TreeViewExpandAllTest.java    License: Apache License 2.0 6 votes vote down vote up
public void doTestExpandAll() throws InterruptedException, InvocationTargetException {

        EventQueue.invokeAndWait(new Runnable() {

            public void run() {
                final BeanTreeView beanTreeView = new BeanTreeView();
                final ExplorerWindow testWindow = new ExplorerWindow();
                testWindow.getContentPane().add(beanTreeView);
                // Node which has 7 levels 0-6
                testWindow.getExplorerManager().setRootContext(new LevelNode(6));

                testWindow.pack();
                testWindow.setVisible(true);
                beanTreeView.expandAll();
            }
        });
        // Whole expanded tree should have nodes O-6
        assertEquals(new HashSet<Integer>(Arrays.asList(0, 1, 2, 3, 4, 5, 6)), expandedNodesIndexes);
    }
 
Example 19
Source Project: netbeans   Source File: MatchingObjectNode.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void nodeDestroyed(NodeEvent ev) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            setInvalidOriginal();
            /**
             * Check if the object is valid again. It can happen when a
             * module with real data loader is enabled.
             */
            RP.post(new Runnable() {

                @Override
                public void run() {
                    checkFileObjectValid();
                }
            }, 2500);
        }
    });
}
 
Example 20
public void processDataConversionRequests() {
    if (EventQueue.isDispatchThread()) {
        AppContext appContext = AppContext.getAppContext();
        getToolkitThreadBlockedHandler().lock();
        try {
            Runnable dataConverter =
                (Runnable)appContext.get(DATA_CONVERTER_KEY);
            if (dataConverter != null) {
                dataConverter.run();
                appContext.remove(DATA_CONVERTER_KEY);
            }
        } finally {
            getToolkitThreadBlockedHandler().unlock();
        }
    }
}
 
Example 21
Source Project: netbeans   Source File: ExplorerActionsImpl.java    License: Apache License 2.0 6 votes vote down vote up
public final void waitFinished() {
    ActionStateUpdater u = actionStateUpdater;
    synchronized (this) {
        u = actionStateUpdater;
    }
    if (u == null) {
        return;
    }
    u.waitFinished();
    if (EventQueue.isDispatchThread()) {
        u.run();
    } else {
        try {
            EventQueue.invokeAndWait(u);
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example 22
Source Project: netbeans   Source File: FormEditorSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Called before regenerating initComponents guarded section to obtain the
 * actual state of the editor fold for the generated code. Needed for the case
 * the user expanded it manually to expand it again after recreating the fold
 * for the new content.
 * @param offset the start offset of the initComponents section
 * @return true if the fold is collapsed, false if expanded
 */
@Override
public Boolean getFoldState(int offset) {
    if (EventQueue.isDispatchThread()) {
        JEditorPane[] panes = getOpenedPanes();
        if (panes != null && panes.length > 0) {
            FoldHierarchy hierarchy = FoldHierarchy.get(panes[0]);
            if (hierarchy != null) {
                try {
                    hierarchy.lock();
                    Fold fold = FoldUtilities.findNearestFold(hierarchy, offset);
                    if (fold != null) {
                        return fold.isCollapsed();
                    }
                } finally {
                    hierarchy.unlock();
                }
            }
        }
    }
    return null;
}
 
Example 23
Source Project: jdk8u60   Source File: X11InputMethod.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Flushes composed and committed text held in this context.
 * This method is invoked in the AWT Toolkit (X event loop) thread context
 * and thus inside the AWT Lock.
 */
// NOTE: This method may be called by privileged threads.
//       This functionality is implemented in a package-private method
//       to insure that it cannot be overridden by client subclasses.
//       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
void flushText() {
    String flush = (committedText != null ? committedText : "");
    if (composedText != null) {
        flush += composedText.toString();
    }

    if (!flush.equals("")) {
        AttributedString attrstr = new AttributedString(flush);
        postInputMethodEvent(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
                             attrstr.getIterator(),
                             flush.length(),
                             null,
                             null,
                             EventQueue.getMostRecentEventTime());
        composedText = null;
        committedText = null;
    }
}
 
Example 24
Source Project: netbeans   Source File: LoggingEventQueue.java    License: Apache License 2.0 6 votes vote down vote up
private EventQueue popQ() {
    try {
        if (popMethod == null) {
            throw new IllegalStateException("Can't access EventQueue.pop");
        }
        EventQueue result = Toolkit.getDefaultToolkit().getSystemEventQueue();
        popMethod.invoke(result, new Object[]{});
        return result;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new IllegalStateException("Can't invoke EventQueue.pop");
        }
    }
}
 
Example 25
Source Project: netbeans   Source File: ManageTagsAction.java    License: Apache License 2.0 6 votes vote down vote up
public void showTagManager (final File repository, final String preselectedTag) {
    GitProgressSupport supp = new GitProgressSupport() {
        @Override
        protected void perform () {
            try {
                GitClient client = getClient();
                Map<String, GitTag> tags = client.getTags(getProgressMonitor(), true);
                final ManageTags createTag = new ManageTags(repository, tags, preselectedTag);
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run () {
                        createTag.show();
                    }
                });
            } catch (GitException ex) {
                GitClientExceptionHandler.notifyException(ex, true);
            }
        }
    };
    supp.start(Git.getInstance().getRequestProcessor(repository), repository, NbBundle.getMessage(ManageTagsAction.class, "LBL_ManageTagsAction.listingTags.progressName")); //NOI18N
}
 
Example 26
Source Project: netbeans   Source File: ToolbarWithOverflowTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testInitOutsideOfEDT() throws Exception {
    class MyToolbar extends ToolbarWithOverflow implements Runnable {

        @Override
        protected void setUI(ComponentUI newUI) {
            assertTrue("Can only be called in EDT", EventQueue.isDispatchThread());
            super.setUI(newUI);
        }

        @Override
        public void setUI(ToolBarUI ui) {
            assertTrue("Can only be called in EDT", EventQueue.isDispatchThread());
            super.setUI(ui);
        }

        private void assertUI() throws Exception {
            EventQueue.invokeAndWait(this);
        }

        @Override
        public void run() {
            assertNotNull("UI delegate is specified", getUI());
        }
    }

    assertFalse("We are not in EDT", EventQueue.isDispatchThread());
    MyToolbar mt = new MyToolbar();
    assertNotNull("Instance created", mt);

    mt.assertUI();
}
 
Example 27
public void run() {
    // If there are no multiple input methods to choose from, wait forever
    while (!hasMultipleInputMethods()) {
        try {
            synchronized (this) {
                wait();
            }
        } catch (InterruptedException e) {
        }
    }

    // Loop for processing input method change requests
    while (true) {
        waitForChangeRequest();
        initializeInputMethodLocatorList();
        try {
            if (requestComponent != null) {
                showInputMethodMenuOnRequesterEDT(requestComponent);
            } else {
                // show the popup menu within the event thread
                EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        showInputMethodMenu();
                    }
                });
            }
        } catch (InterruptedException ie) {
        } catch (InvocationTargetException ite) {
            // should we do anything under these exceptions?
        }
    }
}
 
Example 28
Source Project: netbeans   Source File: ToolbarTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testInitOutsideOfEDT() throws Exception {
    class MyToolbar extends Toolbar implements Runnable {

        @Override
        protected void setUI(ComponentUI newUI) {
            assertTrue("Can only be called in EDT", EventQueue.isDispatchThread());
            super.setUI(newUI);
        }

        @Override
        public void setUI(ToolBarUI ui) {
            assertTrue("Can only be called in EDT", EventQueue.isDispatchThread());
            super.setUI(ui);
        }

        private void assertUI() throws Exception {
            EventQueue.invokeAndWait(this);
        }

        @Override
        public void run() {
            assertNotNull("UI delegate is specified", getUI());
        }
    }
    
    assertFalse("We are not in EDT", EventQueue.isDispatchThread());
    MyToolbar mt = new MyToolbar();
    assertNotNull("Instance created", mt);
    
    mt.assertUI();
}
 
Example 29
/**
 * Initializes the <code>when</code> field if it is not present in the
 * object input stream. In that case, the field will be initialized by
 * invoking {@link java.awt.EventQueue#getMostRecentEventTime()}.
 */
private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
    s.defaultReadObject();
    if (when == 0) {
        // Can't use getMostRecentEventTimeForSource because source is always null during deserialization
        when = EventQueue.getMostRecentEventTime();
    }
}
 
Example 30
Source Project: energy2d   Source File: ScriptDialog.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public void outputScriptResult(final ScriptEvent e) {
	EventQueue.invokeLater(new Runnable() {
		public void run() {
			switch (e.getStatus()) {
			case ScriptEvent.FAILED:
			case ScriptEvent.HARMLESS:
				console.outputError(e.getDescription());
				break;
			case ScriptEvent.SUCCEEDED:
				console.outputEcho(e.getDescription());
				break;
			}
		}
	});
}