Swing requestFocus blues

Max Rydahl Andersen

hmm...was doing some more Swing coding on Hibern8IDE and came across a never ending story - How do you ensure that some component get the first focus when you open up a jdialog, jframe or unhide panel ?

The Component.requestFocus() works great if the compoent is already visible, but often the component is not yet visible and when you make it visible (e.g. someframe.setVisible()) you can't guarantee that it will happen.

The best solution I have found yet is to make an invokeLater() call that makes the correct requestFocus call....but there gotta be another way!

The docs for the new focus manager in JDK 1.4 all talk about the "great new focus manager" but the only problem I got with the old one seem still to be present in the new one....

So, how would you ensure that your a certain component in a JPanel gets the focus when the parent panel gets the focus ? Is there other more declaritive ways than calling table.requestFocus(); just after calling setVisible(true) or in an invokeLater ?



That solves the "when first shown" problem - but how about the problem of being able to just say "somepanel.requestFocus()" and have it make it's first field show focus ?

I don't want to do "somepanel.firstfieldIKnowOff.requestFocus()" - as that breaks the encapsulation.


Just add an inner class - listener of shown event inside your "somepanel" to transfer focus to the disired private field.


Create a nice little anonymous override of the focus event handler for the JPanel (though a type would be better if you want reuse). Then all you have to do is catch the component shown and send a focus event to the panel. The panel would then know what to do with the focus event.