How to find out which object currently has focus

前端 未结 9 812
囚心锁ツ
囚心锁ツ 2020-12-03 13:38

I have a few TextFields in my Frame. I want to know which TextField currently has focus. How can I find this information?

相关标签:
9条回答
  • 2020-12-03 13:50

    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();

    0 讨论(0)
  • 2020-12-03 13:53

    You can get currently focused Component like that:

    Component focusOwner = FocusManager.getCurrentManager().getFocusOwner();
    

    After that You can check if focusOwner is instance of TextField

    0 讨论(0)
  • 2020-12-03 13:56
    KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()
    
    0 讨论(0)
  • 2020-12-03 13:58

    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.

    0 讨论(0)
  • 2020-12-03 14:00

    JFrame.getFocusOwner() (inherited from Window.getFocusOwner()) ought to return a reference to the component with focus. getMostRecentFocusOwner() might also be of interest.

    0 讨论(0)
  • 2020-12-03 14:02

    This tutorial should be pretty helpful to understand focus.

    0 讨论(0)
提交回复
热议问题