Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: debugging with SwingUtilities.invokeLater()

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?

like image 379
Jason S Avatar asked Jan 04 '11 15:01

Jason S


People also ask

What is SwingUtilities invokeLater () used for?

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 javax swing SwingUtilities invokeLater?

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.


1 Answers

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);
    }
}
like image 163
sign Avatar answered Sep 30 '22 03:09

sign