5

I need to get current active window. I have used KeyboardFocusManager, for getting active window. But i am getting active window is null. below is the code. please provide any way to get current active window.

KeyboardFocusManager currentManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();  
Window activeWindow = currentManager.getActiveWindow();
sravani reddy
  • 45
  • 1
  • 2
  • 9

2 Answers2

10

This single line of code should work:

Window activeWindow = javax.swing.FocusManager.getCurrentManager().getActiveWindow();

from the JavaDoc:

Returns the active Window, if the active Window is in the same context as the calling thread. Only a Frame or a Dialog can be the active Window. The native windowing system may denote the active Window or its children with special decorations, such as a highlighted title bar. The active Window is always either the focused Window, or the first Frame or Dialog that is an owner of the focused Window.

to get the GlobalActiveWindow, call:

 javax.swing.FocusManager.getCurrentManager().getGlobalActiveWindow();

JavaDoc:

Returns the active Window, even if the calling thread is in a different context than the active Window. Only a Frame or a Dialog can be the active Window. The native windowing system may denote the active Window or its children with special decorations, such as a highlighted title bar. The active Window is always either the focused Window, or the first Frame or Dialog that is an owner of the focused Window.

Note: When your application does not have the focus, this method returns null!

Cheers!

Ben
  • 3,378
  • 30
  • 46
1

Found the following code and it worked fine for me:

Window getSelectedWindow(Window[] windows) {
    Window result = null;
    for (int i = 0; i < windows.length; i++) {
        Window window = windows[i];
        if (window.isActive()) {
            result = window;
        } else {
            Window[] ownedWindows = window.getOwnedWindows();
            if (ownedWindows != null) {
                result = getSelectedWindow(ownedWindows);
            }
        }
    }
    return result;
} 

And you can call it like this using the static method of class Window:

Window w = getSelectedWindow(Window.getWindows());

Good Luck.

Almost forgot to mention, I've found the recursive method in this site.

STaefi
  • 4,297
  • 1
  • 25
  • 43