Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to activate window in Java?

Tags:

java

swing

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.

  1. use fake transparent undecorated frame that is always on top. This fake window will play role of window B. I did not try to implement it but it seems that it should work.
  2. call 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?

like image 907
AlexR Avatar asked Oct 23 '10 18:10

AlexR


People also ask

What is window in Java?

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.

What is JPanel Swing Java?

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.


1 Answers

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

like image 114
Brad Mace Avatar answered Oct 08 '22 08:10

Brad Mace