I use SwingUtilities.invokeLater()
frequently. Doing so, however, makes it difficult to debug in certain cases: you can't see a stack trace of the code that called SwingUtilities.invokeLater()
, because that code has already ended its execution.
Are there any suggestions for how to set some sort of context (for debugging purposes only) when calling SwingUtilities.invokeLater()
, so that you can figure out what caused the UI event in question?
An invokeLater() method is a static method of the SwingUtilities class and it can be used to perform a task asynchronously in the AWT Event dispatcher thread. The SwingUtilities. invokeLater() method works like SwingUtilities. invokeAndWait() except that it puts the request on the event queue and returns immediately.
What is invokeLater in Java Swing? The invokeLater() is a method in java on swing package and belongs to the SwingUtilities class. Invokelater is used by java swing developer to update or perform any task on Event dispatcher thread asynchronously.
You can try to override EventQueue
and print stacktrace for posted events. Also in the example below a unique number would be assigned to each posted event. When invokeLater
would be called from other invokeLater
then the text postEvent 9 from 7
would be printed in the log
// Place this code somewhere in the main class to override queue EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); eventQueue.push(new MyEventQueue());
Where class MyEventQueue might look like this:
import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.event.InvocationEvent; import java.util.WeakHashMap; public class MyEventQueue extends EventQueue { int currentNumber = 0; WeakHashMap<AWTEvent,Integer> eventIdMap = new WeakHashMap<AWTEvent,Integer>(); AWTEvent currentEvent = null; protected void dispatchEvent(AWTEvent event) { if (event instanceof InvocationEvent) { currentEvent = event; } super.dispatchEvent(event); currentEvent = null; } public void postEvent(AWTEvent event) { if (event instanceof InvocationEvent) { currentNumber = currentNumber + 1; eventIdMap.put(event, currentNumber); System.out.println("postEvent " + currentNumber + " " + (currentEvent != null ? "from " + eventIdMap.get(currentEvent) : "") ); for(StackTraceElement element : new RuntimeException().getStackTrace()) { System.out.println("\t" + element); } } super.postEvent(event); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With