"Always on Top" Windows with Java
In Java, is there a way to have a window that is "Always on top" regardless if the user switches focus to another application? I've searched the web, and all of the solutions lean to some sort of JNI interface with native bindings. Truly this can't be the only way to do it?.. or is it?
Try this method of the Window
class:
Window.setAlwaysOnTop(boolean)
It works the same way as the default in the Windows TaskManager: switch to another app but it shows always on top.
This was added in Java 1.5
Sample code:
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Annoying {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello!!");
// Set's the window to be "always on top"
frame.setAlwaysOnTop( true );
frame.setLocationByPlatform( true );
frame.add( new JLabel(" Isn't this annoying?") );
frame.pack();
frame.setVisible( true );
}
}
Window remains on top even when is not active
From my observation I found that AlwaysOnTop privilege is given to the latest process which requested to be always on top.
So, if you have an application which setAlwaysOnTop(true)
and later another application uses this option, the privilege is given to the second application. In order to work around this I have set the setAlwaysOnTop(false)
and again setAlwaysOnTop(true)
whenever any window comes on top of the current window.
I've checked it with wordweb
in windows
. WordWeb is one of the applications which uses AlwaysOnTop
option from the OS
I'm not sure about if it works properly with your game scenario.
Warning: I'm not aware of the side effects.
Here is the code example:
import java.awt.event.*;
import javax.swing.*;
public class MainWindow extends JFrame implements WindowFocusListener
{
public MainWindow()
{
addWindowFocusListener(this);
setAlwaysOnTop(true);
this.setFocusable(true);
// this.setFocusableWindowState(true);
panel = new JPanel();
//setSize(WIDTH,HEIGHT);
setUndecorated(true);
setLocation(X,Y);
setExtendedState(MAXIMIZED_BOTH);
setVisible(true);
}
public void windowGainedFocus(WindowEvent e){}
public void windowLostFocus(WindowEvent e)
{
if(e.getNewState()!=e.WINDOW_CLOSED){
//toFront();
//requestFocus();
setAlwaysOnTop(false);
setAlwaysOnTop(true);
//requestFocusInWindow();
System.out.println("focus lost");
}
}
private JPanel panel;
private static final int WIDTH = 200;
private static final int HEIGHT = 200;
private static final int X = 100;
private static final int Y = 100;
public static void main(String args[]){
new MainWindow();}
}