Q:

Java - cannot bring the window to front

I am trying to execute the following code:
SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                if (frame.getExtendedState() == Frame.ICONIFIED)
                                    frame.setExtendedState(Frame.NORMAL);
                                frame.getGlassPane().setVisible(!frame.getGlassPane().isVisible());

                                frame.toFront();
                                frame.repaint();

                            }
                        });

Unfortunately this does not bring it to the front from behind other windows...  Any solutions?

A:

Per the API documentation for setExtendedState: 

If the frame is currently visible on the screen (the
  Window.isShowing() method returns true), the developer should examine
  the return value of the WindowEvent.getNewState() method of the
  WindowEvent received through the WindowStateListener to determine that
  the state has actually been changed.
If the frame is not visible on the screen, the events may or may not
  be generated. In this case the developer may assume that the state
  changes immediately after this method returns. Later, when the
  setVisible(true) method is invoked, the frame will attempt to apply
  this state. Receiving any WindowEvent.WINDOW_STATE_CHANGED events is
  not guaranteed in this case also.

However, there is also a windowDeiconified callback you can hook into on WindowListener:
SwingUtilities.invokeLater(new Runnable() {
  private final WindowListener l = new WindowAdapter() {
    @Override
    public void void windowDeiconified(WindowEvent e) {
      // Window now deiconified so bring it to the front.
      bringToFront();

      // Remove "one-shot" WindowListener to prevent memory leak.
      frame.removeWindowListener(this);
    }
  };

  public void run() {
    if (frame.getExtendedState() == Frame.ICONIFIED) {
      // Add listener and await callback once window has been deiconified.
      frame.addWindowListener(l);
      frame.setExtendedState(Frame.NORMAL);
    } else {
      // Bring to front synchronously.
      bringToFront();
    }
  }

  private void bringToFront() {
    frame.getGlassPane().setVisible(!frame.getGlassPane().isVisible());
    frame.toFront();
    // Note: Calling repaint explicitly should not be necessary.
  }
});

A:

I found that the following workaround for toFront() on a JDialog works on Windows 7 (haven't tested other platforms yet):
boolean aot = dialog.isAlwaysOnTop();
dialog.setAlwaysOnTop(true);
dialog.setAlwaysOnTop(aot);

Paul van Bemmelen

