Windows has the facility to prevent windows from stealing focus; instead it flashes the taskbar icon. In XP it's on by default (the only place I've seen to change it is using TweakUI, but there is a registry setting somewhere). In Vista they may have changed the default and/or exposed it as a user accessible setting with the out-of-the-box UI.
Preventing windows from forcing themselves to the front and taking focus is a feature since Windows 2K (and I, for one, am thankful for it).
That said, I have a little Java app I use to remind me to record my activities while working, and it makes itself the active window every 30 minutes (configurable, of course). It always works consistently under Windows XP and never flashes the title bar window. It uses the following code, called in the UI thread as a result of a timer event firing:
if(getState()!=Frame.NORMAL) { setState(Frame.NORMAL); }
toFront();
repaint();
(the first line restores if minimized... actually it would restore it if maximized too, but I never have it so).
While I usually have this app minimized, quite often it's simply behind my text editor. And, like I said, it always works.
I do have an idea on what your problem could be - perhaps you have a race condition with the setVisible() call. toFront() may not be valid unless the window is actually displayed when it is called; I have had this problem with requestFocus() before. You may need to put the toFront() call in a UI listener on a window activated event.
2014-09-07: At some point in time the above code stopped working, perhaps at Java 6 or 7. After some investigation and experimentation I had to update the code to override the window's toFront
method do this (in conjunction with modified code from what is above):
setVisible(true);
toFront();
requestFocus();
repaint();
...
public @Override void toFront() {
int sta = super.getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL;
super.setExtendedState(sta);
super.setAlwaysOnTop(true);
super.toFront();
super.requestFocus();
super.setAlwaysOnTop(false);
}
As of Java 8_20, this code seems to be working fine.
toFront()
on the EDT usinginvokeLater
. There is a simple answer included below, but it is not the accepted answer. It does work, though. Perfectly. – Agent