Java Swing How to - Position JOptionPane.showMessageDialog at the center of screen?








Question

We would like to know how to position JOptionPane.showMessageDialog at the center of screen?.

Answer

import java.awt.Component;
/*from  ww  w . j  av a2 s .  c  o  m*/
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Main {

  public static void main(String[] args) {
    int result = JOptionPane.showConfirmDialog(null, "Show over parent?");
    for (int i = 1; i < 4; i++) {
      JFrame f = new JFrame("Frame " + i);
      f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      Component parent = (JOptionPane.OK_OPTION == result ? f : null);

      f.setSize(400, 300);
      f.setLocationByPlatform(true);
      f.setVisible(true);

      JDialog d = new JDialog(f);
      d.setTitle("Dialog " + i);
      d.setSize(300, 200);
      d.setLocationRelativeTo(parent);
      d.setVisible(true);
    }
  }
}