类java.awt.EventQueue源码实例Demo

下面列出了怎么用java.awt.EventQueue的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: TencentKona-8   文件: SwingUtilities3.java
@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");
}
 
源代码2 项目: netbeans   文件: RevertPanel.java
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
    }
}
 
源代码3 项目: Pixelitor   文件: PreferencesPanel.java
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."));
        }
    });
}
 
源代码4 项目: FlatLaf   文件: FlatLaf.java
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 );
		}
	} );
}
 
源代码5 项目: FlatLaf   文件: FlatLaf.java
/**
 * 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;
		}
	} );
}
 
源代码6 项目: netbeans   文件: RemoteStyleSheetCache.java
/**
 * 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);
            }
        });
    }
}
 
源代码7 项目: netbeans   文件: HTMLDialogImpl.java
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;
}
 
源代码8 项目: netbeans   文件: StatusTest.java
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];
    }
}
 
源代码9 项目: jdk8u-dev-jdk   文件: X11InputMethod.java
/**
 * 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;
    }
}
 
源代码10 项目: netbeans   文件: AnnotationBar.java
/**
 * 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
    }
}
 
源代码11 项目: netbeans   文件: TopLoggingAWTTest.java
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);
}
 
源代码12 项目: netbeans   文件: RepositoryBrowserPanel.java
@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 };
}
 
源代码13 项目: netbeans   文件: HgVersioningTopComponent.java
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();
    }
}
 
@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();
                    }
                }
            });
        }
    });
}
 
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);
        }
    });
}
 
源代码16 项目: dragonwell8_jdk   文件: X11InputMethod.java
/**
 * 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;
    }
}
 
源代码17 项目: Ardulink-1   文件: SimpleSmartCarDriver.java
/**
 * 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();
			}
		}
	});
}
 
源代码18 项目: netbeans   文件: TreeViewExpandAllTest.java
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);
    }
 
源代码19 项目: netbeans   文件: MatchingObjectNode.java
@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);
        }
    });
}
 
源代码20 项目: openjdk-8-source   文件: DataTransferer.java
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();
        }
    }
}
 
源代码21 项目: netbeans   文件: ExplorerActionsImpl.java
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);
        }
    }
}
 
源代码22 项目: netbeans   文件: FormEditorSupport.java
/**
 * 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;
}
 
源代码23 项目: jdk8u60   文件: X11InputMethod.java
/**
 * 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;
    }
}
 
源代码24 项目: netbeans   文件: LoggingEventQueue.java
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");
        }
    }
}
 
源代码25 项目: netbeans   文件: ManageTagsAction.java
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
}
 
源代码26 项目: netbeans   文件: ToolbarWithOverflowTest.java
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();
}
 
源代码27 项目: jdk8u-jdk   文件: ExecutableInputMethodManager.java
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?
        }
    }
}
 
源代码28 项目: netbeans   文件: ToolbarTest.java
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();
}
 
源代码29 项目: jdk8u-dev-jdk   文件: InputMethodEvent.java
/**
 * 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();
    }
}
 
源代码30 项目: energy2d   文件: ScriptDialog.java
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;
			}
		}
	});
}