下面列出了java.awt.EventQueue#invokeLater() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** Scroll a text area to display a given position near the middle of the visible area. */
private void scroll(final JTextArea t, final int pos) {
// Using invokeLater appears to give text a chance to sort itself out
// before the scroll happens; otherwise scrollRectToVisible doesn't work.
// Maybe there's a better way to sync with the text...
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Rectangle r = t.modelToView(pos);
JScrollPane p = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, t);
r.y = Math.max(0, r.y - p.getHeight() * 2 / 5);
r.height += p.getHeight() * 4 / 5;
t.scrollRectToVisible(r);
} catch (BadLocationException ignore) {
}
}
});
}
private static void launchGui() {
log(VERSION);
log("No arguments passed. Launching gui...");
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
BON2Gui frame = new BON2Gui();
frame.setVisible(true);
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public void perform () {
try {
final DefaultListModel targetsModel = new DefaultListModel();
targetsModel.addElement(INITIAL_REVISION);
EventQueue.invokeLater(new Runnable() {
@Override
public void run () {
panel.branchList.setModel(targetsModel);
if (!targetsModel.isEmpty()) {
panel.branchList.setSelectedIndex(0);
}
}
});
refreshRevisions(this);
} finally {
loadingSupport = null;
}
}
public void removeAllModels() {
if (View.isInitialised() && !EventQueue.isDispatchThread()) {
EventQueue.invokeLater(
new Runnable() {
@Override
public void run() {
removeAllModels();
}
});
return;
}
int lastIndex = Math.max(models.size() - 1, 0);
models.clear();
models.trimToSize();
abstractTableModel.fireTableRowsDeleted(0, lastIndex);
}
protected void addTokenResult(final MessageSummary msg) {
if (EventQueue.isDispatchThread()) {
resultsModel.addMessage(msg);
if (msg.isGoodResponse()) {
getProgressBar().setValue(getProgressBar().getValue() + 1);
}
return;
}
try {
EventQueue.invokeLater(
new Runnable() {
@Override
public void run() {
addTokenResult(msg);
}
});
} catch (Exception e) {
}
}
/**
* Checks change of the <code>DataFlavor</code>s and, if necessary,
* notifies all listeners that have registered interest for notification
* on <code>FlavorEvent</code>s.
*
* @since 1.5
*/
private void fireFlavorsChanged() {
if (flavorListeners == null) {
return;
}
Set<DataFlavor> prevDataFlavors = currentDataFlavors;
currentDataFlavors = getAvailableDataFlavorSet();
if (prevDataFlavors.equals(currentDataFlavors)) {
return;
}
FlavorListener[] flavorListenerArray =
(FlavorListener[])flavorListeners.getListenersInternal();
for (int i = 0; i < flavorListenerArray.length; i++) {
final FlavorListener listener = flavorListenerArray[i];
EventQueue.invokeLater(new Runnable() {
public void run() {
listener.flavorsChanged(new FlavorEvent(Clipboard.this));
}
});
}
}
/**
* Silly workaround function.
*
* @param panel The panel to initialize.
*/
private void workArounds(final CGraphPanel panel) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
panel.updateSplitters();
workaroundCase874(panel.getModel().getGraph());
}
});
}
/**
* Change the current display name.
*/
public void setName(String n) {
String oldGroupName = getNameOrNull();
prefs().put(KEY_NAME, n);
notifyListeners(this, "groupRename", oldGroupName, n);
if (this.equals(getActiveGroup())) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
ProjectTab.findDefault(ProjectTab.ID_LOGICAL).setGroup(Group.this);
}
});
}
}
/**
* Creates {@code selectedNodeListner}.
*
* @return {@code selectedNodeListner}.
*/
private PropertyChangeListener createSelectedNodeListener() {
return new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (isShowing() && !glassPane.isUserActionInProgress()) {
if (!updateScheduled) {
// This method is called several times when a change
// is done to some property (in property sheet)
// when several components are selected.
// Avoiding partial refresh - waiting till
// other invocations/property modifications
// are finished.
updateScheduled = true;
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
updateScheduled = false;
glassPane.updateLayout();
updateCustomizer();
}
});
}
}
}
};
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TemplateVarGainJframe frame = new TemplateVarGainJframe();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
leak();
}
});
}
@SuppressWarnings("LeakingThisInConstructor")
public ActiveConfigAction() {
super();
putValue("noIconInMenu", true); // NOI18N
EventQueue.invokeLater(new Runnable() {
public @Override void run() {
initConfigListCombo();
}
});
lst = new PropertyChangeListener() {
public @Override void propertyChange(PropertyChangeEvent evt) {
ProjectConfigurationProvider<?> _pcp;
synchronized (ActiveConfigAction.this) {
_pcp = pcp;
}
if (ProjectConfigurationProvider.PROP_CONFIGURATIONS.equals(evt.getPropertyName())) {
configurationsListChanged(_pcp != null ? getConfigurations(_pcp) : null);
} else if (ProjectConfigurationProvider.PROP_CONFIGURATION_ACTIVE.equals(evt.getPropertyName())) {
activeConfigurationChanged(_pcp != null ? getActiveConfiguration(_pcp) : null);
}
}
};
looklst = new LookupListener() {
public @Override void resultChanged(LookupEvent ev) {
activeProjectProviderChanged();
}
};
OpenProjectList.getDefault().addPropertyChangeListener(WeakListeners.propertyChange(this, OpenProjectList.getDefault()));
lookup = LookupSensitiveAction.LastActivatedWindowLookup.INSTANCE;
Lookup.Result<Project> resultPrj = lookup.lookupResult(Project.class);
Lookup.Result<DataObject> resultDO = lookup.lookupResult(DataObject.class);
resultPrj.addLookupListener(WeakListeners.create(LookupListener.class, this, resultPrj));
resultDO.addLookupListener(WeakListeners.create(LookupListener.class, this, resultDO));
refreshView(lookup);
}
@Override
public void run() {
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(this);
return;
}
displayOutput(output);
}
@Override
public boolean onHandshakeResponse(
HttpMessage httpMessage, Socket inSocket, ZapGetMethod method) {
boolean keepSocketOpen = false;
if (httpMessage.isWebSocketUpgrade()) {
logger.debug(
"Got WebSockets upgrade request. Handle socket connection over to WebSockets extension.");
if (focusWebSocketsTabOnHandshake) {
// Don't constantly request focus on the tab, once is enough.
focusWebSocketsTabOnHandshake = false;
EventQueue.invokeLater(
() -> {
// Show the tab in case its been closed
this.getWebSocketPanel().setTabFocus();
});
}
if (method != null) {
Socket outSocket = method.getUpgradedConnection();
InputStream outReader = method.getUpgradedInputStream();
keepSocketOpen = true;
addWebSocketsChannel(httpMessage, inSocket, outSocket, outReader);
} else {
logger.error("Unable to retrieve upgraded outgoing channel.");
}
}
return keepSocketOpen;
}
@Override
public void performAction() {
final T t = result.allInstances().iterator().next();
// Ensure it's AWT event thread
EventQueue.invokeLater(new Runnable() {
public void run() {
performAction(t);
}
});
}
private void startUpdate() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
ConfigSettings.initConfig(System.getProperty("user.dir"));
} catch (IOException ex) {
Logger.getLogger("FrmMain.FrmMain").log(Level.SEVERE, null, ex);
}
}
});
}
/**
* Sets the current contents of the clipboard to the specified
* transferable object and registers the specified clipboard owner
* as the owner of the new contents.
* <p>
* If there is an existing owner different from the argument
* <code>owner</code>, that owner is notified that it no longer
* holds ownership of the clipboard contents via an invocation
* of <code>ClipboardOwner.lostOwnership()</code> on that owner.
* An implementation of <code>setContents()</code> is free not
* to invoke <code>lostOwnership()</code> directly from this method.
* For example, <code>lostOwnership()</code> may be invoked later on
* a different thread. The same applies to <code>FlavorListener</code>s
* registered on this clipboard.
* <p>
* The method throws <code>IllegalStateException</code> if the clipboard
* is currently unavailable. For example, on some platforms, the system
* clipboard is unavailable while it is accessed by another application.
*
* @param contents the transferable object representing the
* clipboard content
* @param owner the object which owns the clipboard content
* @throws IllegalStateException if the clipboard is currently unavailable
* @see java.awt.Toolkit#getSystemClipboard
*/
public synchronized void setContents(Transferable contents, ClipboardOwner owner) {
final ClipboardOwner oldOwner = this.owner;
final Transferable oldContents = this.contents;
this.owner = owner;
this.contents = contents;
if (oldOwner != null && oldOwner != owner) {
EventQueue.invokeLater(new Runnable() {
public void run() {
oldOwner.lostOwnership(Clipboard.this, oldContents);
}
});
}
fireFlavorsChanged();
}
/**
* @see java.awt.im.InputContext#removeNotify
* @exception NullPointerException when the component is null.
*/
public synchronized void removeNotify(Component component) {
if (component == null) {
throw new NullPointerException();
}
if (inputMethod == null) {
if (component == currentClientComponent) {
currentClientComponent = null;
}
return;
}
// We may or may not get a FOCUS_LOST event for this component,
// so do the deactivation stuff here too.
if (component == awtFocussedComponent) {
focusLost(component, false);
}
if (component == currentClientComponent) {
if (isInputMethodActive) {
// component wasn't the one that had the focus
deactivateInputMethod(false);
}
inputMethod.removeNotify();
if (clientWindowNotificationEnabled && addedClientWindowListeners()) {
removeClientWindowListeners();
}
currentClientComponent = null;
if (inputMethod instanceof InputMethodAdapter) {
((InputMethodAdapter) inputMethod).setClientComponent(null);
}
// removeNotify() can be issued from a thread other than the event dispatch
// thread. In that case, avoid possible deadlock between Component.AWTTreeLock
// and InputMethodContext.compositionAreaHandlerLock by releasing the composition
// area on the event dispatch thread.
if (EventQueue.isDispatchThread()) {
((InputMethodContext)this).releaseCompositionArea();
} else {
EventQueue.invokeLater(new Runnable() {
public void run() {
((InputMethodContext)InputContext.this).releaseCompositionArea();
}
});
}
}
}
protected void updateJBRHitTestSpotsAndTitleBarHeightLater() {
EventQueue.invokeLater( () -> {
updateJBRHitTestSpotsAndTitleBarHeight();
} );
}
private void adjustSize() {
if (!mSizePending) {
mSizePending = true;
EventQueue.invokeLater(() -> runAdjustSize());
}
}