|
Java™ by example!
|
|
|
How do I query for the currently focused Component?
Well, there is a method in Window named getFocusOwner which returns the currently focused child of the window on which you invoke the method. Given that and the Frame.getFrames() method which returns all the frames created by the application, all you have to do is iterate over all the frames and find the focused component like this:
 public static Component findFocusedComponent(){ Frame [] allFrames = Frame.getFrames(); for (int i=0;i<allFrames.length;i++){ Frame frame = allFrames[i]; Component focusOwner = frame.getFocusOwner(); if (focusOwner!=null) return focusOwner; } return null; // if no focused component exists }
|
The only question remains to be answered before we've proved that our method works is "Why couldn't there be any Windows or Dialogs (and not Frames) that have a focused child?". The answer to that question is that the only component which doesn't have a parent is Frame - this means that even if there is such a Window or Dialog, it must have a Frame parent, whom we checked in our method...
Further Information
Author of answer: Alexander Maryanovsky
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|