下面列出了怎么用java.awt.EventQueue的API类实例代码及写法,或者点击链接到github查看源代码。
@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");
}
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
}
}
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."));
}
});
}
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 );
}
} );
}
/**
* 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;
}
} );
}
/**
* 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);
}
});
}
}
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;
}
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];
}
}
/**
* 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;
}
}
/**
* 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
}
}
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);
}
@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 };
}
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);
}
});
}
/**
* 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;
}
}
/**
* 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();
}
}
});
}
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);
}
@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);
}
});
}
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();
}
}
}
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);
}
}
}
/**
* 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;
}
/**
* 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;
}
}
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");
}
}
}
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
}
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();
}
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?
}
}
}
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();
}
/**
* 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();
}
}
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;
}
}
});
}