Making a non-focusable Window focusable
By kannan on Apr 22, 2008
I recently came across another issue from a customer where an awt Window component was not getting focus even when requested.
java.awt.Window or javax.swing.JWindow class is typically used by customer for creating customized popup menus or tooltips or as a splash screen (We now have SplashScreen class introduced in java.awt package in 6.0).
A Window component is created with lots of awt Label components inside it where each Label component is treated as a menu item
It's well documented that for a Window to be focusable, its owner (either a Frame or another Window object) needs to be showing on the screen.
In this case, the customer had a Frame as its owner but still couldn't make the Window focusable. Why?
There is one more condition for a Window component to be focusable that users may not remember and is documented somewhere in the middle of the AWT Focus specification.
These are the wordings in AWT Focus Specification:
"Every Window which is not a Frame or Dialog, but whose nearest owning Frame or Dialog is showing on the screen, and which has at least one Component in its focus traversal cycle, is also focusable by default. "
Since customer's Window contains only Label(s) and a panel (none of which are focusable by default), the window is not focusable and hence even adding keylistener to the Window object has no effect.
There are two solutions to this:
1. Call Window.setFocusable(true) OR
2. Reset the focus traversal policy of the window to ContainerOrderFocusTraversalPolicy.
The first one is much simpler I believe.