I have a few TextField
s in my Frame
. I want to know which TextField
currently has focus. How can I find this information?
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()
;
wont work across threads. So if your app invokes a new thread and that thread has its own frame/window etc then it wont be able to gain the focus owner from that thread. Instead use: KeyboardFocusManager.getCurrentKeyboardFocusManager().getGlobalFocusOwner();
You can get currently focused Component like that:
Component focusOwner = FocusManager.getCurrentManager().getFocusOwner();
After that You can check if focusOwner
is instance of TextField
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()
Every JComponent has a hasFocus method that you can use to check if it has focus. However, this has been changed, and now you should use isFocusOwner.
So run over all the text fields in your frame, and check on each of them if it is isFocusOwner by calling that method.
You could also get the focus owner through the frame.
JFrame.getFocusOwner()
(inherited from Window.getFocusOwner()) ought to return a reference to the component with focus. getMostRecentFocusOwner()
might also be of interest.
This tutorial should be pretty helpful to understand focus.