Obviously, this question already exists here. And over here someone answered it similarly. However, I tried both approaches (as I pointed out) and neither seems to work for me. I'm on Java 8 Update 22 on Windows 10, whereas the poster on that last post is not on Windows and on Java 7, so maybe one of these things has something to do with it. Code I have tried, where getInstance()
is my JFrame object:
private static void bringToFront() {
getInstance().setVisible(true);
getInstance().setExtendedState(JFrame.NORMAL);
getInstance().toFront();
getInstance().repaint();
}
private static void bringToFront() {
getInstance().setVisible(true);
getInstance().toFront();
getInstance().requestFocus();
getInstance().repaint();
}
@Override
public void toFront() {
int sta = super.getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL;
super.setExtendedState(sta);
super.setAlwaysOnTop(true);
super.toFront();
super.requestFocus();
super.setAlwaysOnTop(false);
}
Note that I do not want the window to always stay on top. However, with that last snippet it does stay on top.
EDIT: I now realise it doesn't always stay on top. The problem is that it the window appears on top at first, but doesn't have focus (the icon in the task bar is flickering), meaning that if a user clicks somewhere else than the window the window will stay on top because it isn't "losing focus", as it didn't have any to begin with. I tried requestFocus()
but that didn't work either. Probably because of this explanation. How can I make sure the window has focus on initial pop-up?
I tried mKorbel's solution, but that didn't work either. It works only when the window has already appeared and has been activated, and de-activated and when then the method is called, the window comes to the front. However, when first initialising the window, it doesn't show up to the front.
private static void bringToFront() {
getInstance().setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
getInstance().toFront();
}
});
getInstance().requestFocus();
getInstance().repaint();
}