java.awt.EventQueue Java Examples

The following examples show how to use java.awt.EventQueue. 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 check out the related API usage on the sidebar.
Example #1
Source File: ManageTagsAction.java    From netbeans with 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 #2
Source File: RevertPanel.java    From netbeans with 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 File: SwingUtilities3.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@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 #4
Source File: PreferencesPanel.java    From Pixelitor with 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 #5
Source File: FlatLaf.java    From FlatLaf with 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 #6
Source File: FlatLaf.java    From FlatLaf with 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 #7
Source File: RemoteStyleSheetCache.java    From netbeans with 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 #8
Source File: HTMLDialogImpl.java    From netbeans with 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 #9
Source File: StatusTest.java    From netbeans with 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 #10
Source File: X11InputMethod.java    From jdk8u-dev-jdk with 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 #11
Source File: AnnotationBar.java    From netbeans with 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 #12
Source File: TopLoggingAWTTest.java    From netbeans with 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 #13
Source File: RepositoryBrowserPanel.java    From netbeans with 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 #14
Source File: FeatureOnDemandWizardIteratorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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 #15
Source File: CodeSnifferStandardsComboBoxModel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: LoggingEventQueue.java    From netbeans with 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 #17
Source File: X11InputMethod.java    From jdk8u60 with 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 #18
Source File: FormEditorSupport.java    From netbeans with 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 #19
Source File: ExplorerActionsImpl.java    From netbeans with 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 #20
Source File: DataTransferer.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
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 File: MatchingObjectNode.java    From netbeans with 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 #22
Source File: TreeViewExpandAllTest.java    From netbeans with 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 #23
Source File: SimpleSmartCarDriver.java    From Ardulink-1 with 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 #24
Source File: X11InputMethod.java    From dragonwell8_jdk with 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 #25
Source File: HgVersioningTopComponent.java    From netbeans with 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 #26
Source File: ScriptDialog.java    From energy2d with 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;
			}
		}
	});
}
 
Example #27
Source File: ToolbarTest.java    From netbeans with 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 #28
Source File: GitAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
@NbBundle.Messages({
    "MSG_GitAction.actionDisabled=Action cannot be executed,\nit is disabled in the current context.",
    "MSG_GitAction.savingFiles.progress=Preparing Git action"
})
protected final void performAction(final Node[] nodes) {
    final AtomicBoolean canceled = new AtomicBoolean(false);
    Runnable run = new Runnable() {

        @Override
        public void run () {
            if (!enableFull(nodes)) {
                Logger.getLogger(GitAction.class.getName()).log(Level.INFO, "Action got disabled, execution stopped");
                DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(Bundle.MSG_GitAction_actionDisabled()));
                return;
            }
            LifecycleManager.getDefault().saveAll();
            Utils.logVCSActionEvent("Git"); //NOI18N
            if (!canceled.get()) {
                EventQueue.invokeLater(new Runnable() {

                    @Override
                    public void run () {
                        performContextAction(nodes);
                    }
                });
            }
        }
    };
    ProgressUtils.runOffEventDispatchThread(run, Bundle.MSG_GitAction_savingFiles_progress(), canceled, false);
}
 
Example #29
Source File: InputMethodEvent.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 File: PropertyPanelTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testCanComputePreferredSize() throws Exception {
    final PropertyPanel pp = new PropertyPanel();
    assertNotNull("Don't throw an exception", pp.getPreferredSize());
    
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            pp.addNotify();
            assertNotNull("Don't throw an exception", pp.getPreferredSize());
        }
    });
}