I would like to activate my Swing application programatically. I mean that I would like to write code that cause the JFrame
to be visible and focused (the window header should be highlighted).
I tried to use requestFocus()
. It works only if application has at least 2 windows A and B: A is hidden, B is visible. Now if I call A.requestFocus()
it becomes active as I want. It does not happen if application has only one window or if both windows are invisible.
I found 2 workarounds.
A.setAlwaysOnTop(true)
. This brings window A on top of other windows. But it is not in focus yet. Use java.awt.Robot
(mouseMove, mousePress, mouseRelease) to make a click on the header of window A.
Now call A.setAlwaysOnTop(false)
and return mouse pointer back to its previous position.
I implemented the code and it works but it looks like an ugly workaround. Is there a "right" solution?
A Window object is a top-level window with no borders and no menubar. The default layout for a window is BorderLayout . A window must have either a frame, dialog, or another window defined as its owner when it's constructed.
The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class. It doesn't have title bar.
frame.setState(Frame.NORMAL); // restores minimized windows
frame.toFront(); // brings to front without needing to setAlwaysOnTop
frame.requestFocus();
for everything you could want to know in excruciating detail, see this page: http://www.developer.com/java/other/article.php/3502181/Window-Focus-and-State-in-Java.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With