how to show JOptionPane on the top of all windows

itro picture itro · Jun 4, 2012 · Viewed 35.8k times · Source

I have created a DialogUtil which shows numbers of JOptionPan in different situation. sometimes in my action class call to this method with null parameters as below.

DialogUtil.showNotExist(null,xml.getName().concat(" is null or"));

In this case JOptionPane does not appears on the top of window.

How can I add something to JOptionPane to appears always on the top?

public static void showNotExist(JPanel panel, String action) {
    JOptionPane.showMessageDialog(panel, new JLabel(action.concat(" doesn't exist."), 2));
}

Answer

Enwired picture Enwired · Jun 9, 2012

Have you tried something like this?

JOptionPane optionPane = new JOptionPane();
JDialog dialog = optionPane.createDialog("Title");
dialog.setAlwaysOnTop(alwaysOnTop);
dialog.setVisible(true);

There is no guarantee that the operating system will allow your dialog to be always on top, but it will often work.

If you have an existing window or dialog and you want to bring it to the top, but don't want to permanently set alwaysOnTop, this should work while leaving the old value of alwaysOnTop alone:

boolean supported = window.isAlwaysOnTopSupported();
boolean old_alwaysOnTop = window.isAlwaysOnTop();
if (supported) {
  window.setAlwaysOnTop(true);
}
window.toFront();
window.requestFocus();
if (supported) {
  window.setAlwaysOnTop(old_alwaysOnTop);
}

Run that code only on the SwingThread.