Home > Enterprise >  How to find the JComponent which has focus within a Swing application?
How to find the JComponent which has focus within a Swing application?

Time:03-22

I am having problems to identify where the focus within my application goes to after activating/deactivating or opening/closing some dialogs.

Is there a way to safely get an event down handed down the component hierarchy to be informed when the focus changes and where to?

In a Smalltalk environment for instance, you could for testing reasons just re-implement #requestFocus on Window/SubPane (i.e. JComponent) level and have a debug statement where the focus went.

Can you do something like that in Java or is there a mechanism I am missing?

CodePudding user response:

I'm not entirely sure what you're trying to do with this, but to answer your question you could add a FocusListener to each element. An avriable is then written using the FocusGained function.

int focus = 0;
textField1.addFocusListener(new FocusListener() {
        @Override
    
        public void focusGained(FocusEvent e) {
            focus = 1;                    
        }
    
        @Override
        public void focusLost(FocusEvent e) {
            
        }
    });

textField2.addFocusListener(new FocusListener() {
        @Override
    
        public void focusGained(FocusEvent e) {
            focus = 2;                    
        }
    
        @Override
        public void focusLost(FocusEvent e) {
            
        }
    });
  • Related