Focus debugging in Java

Question:

I'm trying to debug some focus related issues in my Java Swing application. Sometimes, some components seem to be catching the focus, and I can't determine where in the code

I tried

>Vetoablechangelistener. Using keyboardfocusmanager (for focusowner) This gives me information about which components are missing and gain focus, but it doesn't help me point out which priorities are required in the code. > Customize keyboardfocusmanager However, I can also intervene when I receive an event By then, the call stack for the call to requestfocus has been lost. > Custom eventqueue But I can also intervene in the dispatchEvent method called from EDT The call stack is lost again (interestingly, postevent (awtevent) is not called)

Question:

When I call requestfocusinwindow, what I'm looking for is the call stack Can I get this information Perhaps, if I can redefine the method used to publish events in eventqueue, I can print the stack dump But eventqueue Postevent (awtevent) will not be called

Anyone can come up with a solution that will help me get the status of the stack when I call requestfocus or requestfocusinwindow?

Solution

It seems that they (the sun) really don't want you to do this At first glance, there seems to be no virtual method that can be easily covered in this path, rather than in EventQueue (PostEvent is used for invokelater and application code synthesis events), and is not used in KeyboardFocusManager (as you can see, the scheduling loop later calls the override method).

Fortunately, if you're using sun JRE, you can insert a code, but it's not beautiful:

Component. Requestfocus() calls the static keyboardfocusmanager Setmostrecentfocusowner (component), which updates a private static map named mostrecentfocusowners

Therefore, if you can access a static map using reflection, you can replace it with a forward map that traces the call to the put method:

import com.google.common.collect.ForwardingMap;

// ...

Field mrfoField = KeyboardFocusManager.class.getDeclaredField("mostRecentFocusOwners");
mrfoField.setAccessible(true);
final Map delegate = (Map) mrfoField.get(null);
Map mrfo = new ForwardingMap() {
    public Object put(Object key,Object value) {
        new Throwable().printStackTrace();
        return super.put(key,value);
    }
    protected Map delegate() {
        return delegate;
    }
};
mrfoField.set(null,mrfo);

This will capture the call to requestfocus and give you a stack trace

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>