Use a [url=http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/FocusListener.html]FocusListener[/url] and the [url=http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Window.html#toFront()]toFront()[/url] method. This will not work 100% of the time, though. By the way, JFrame is a Swing component, and this should have been posted in the Swing forum.
I said it would not work 100% of the time. Write a test program, it does work most of the time.
import javax.swing.JFrame;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class WindowOnTop extends JFrame
{
public WindowOnTop()
{
addFocusListener(new FocusAdapter()
{
public void focusLost(FocusEvent e)
{
requestFocus();
toFront();
}
});
setSize(500, 500);
setLocation(20, 20);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new WindowOnTop();
}
}
> You only get the focusLost event if the JFrame is in
> focus.
> And there's no way to get the focus back from the
> OS.
Look at my example program. I requested focus before moving it to the front. It does work, try it out.
> Read here:
> http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Windo
> w.html#toFront()
> In Windows for example toFront has no affect.
We're talking about JFrames, not Windows.
I meant Windows OS.
Window is an ancestor of JFrame and uses toFront of Window class.
I tried it, and it doestn't work.
Anyway it's a nice idea in theory but not a practical one, since grabbing the focus from the application the user wanted to be in focus is a bad thing.
All the AlwaysOnTop uses I know of aren't meant to prevent the user from using other applications.
> I meant Windows OS.
Ah, you need to specify these things. ;-)
> Window is an ancestor of JFrame and uses toFront of
> Window class.
> I tried it, and it doestn't work.
Works for me. I have Windows XP SP2.
> Anyway it's a nice idea in theory but not a practical
> one, since grabbing the focus from the application
> the user wanted to be in focus is a bad thing.
> All the AlwaysOnTop uses I know of aren't meant to
> prevent the user from using other applications.
I know, I was just suggesting this to the OP because I know no other way to do it using java.
That's strange.
I'm using WIndows 2000 SP4 and requestFocus + toFront has no affect.
What JDK are you using?
I know there's a DLL+ JNI interface ready for use (Windows OS) somewhere in the forum that has setAlwaysOnTop functionality, because I was looking for the same thing some time ago and found it.
I implemented it myself using JNI because I already use JNI in my application.