How to find out which object currently has focus

前端 未结 9 813
囚心锁ツ
囚心锁ツ 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 14:03

    getFocusOwner() will return the child component which is currently focused.

    But you have to check to see if it is a JTextField. Other components like buttons might be focused if they exist in your frame as well.

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

    You could also listen for the appropriate property change in keyboard focus manager:

    KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            System.out.println(evt.getNewValue());
        }
    });
    

    This outputs focus owner as you interact with Swing components and is useful for debugging focus issues in general.

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

    Also have a look at the javax.swing.FocusManager

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