How to center a Java JDialog

Java/Swing FAQ: How do I center a JDialog?

Answer: The answer here really depends on what you mean by "center". If you really want to center a JDialog on screen, you can use code like this:

// center a jdialog on screen
JDialog d = new JDialog();
d.setSize(400, 300);
d.setLocationRelativeTo(null);
d.setVisible(true);

By calling setLocationRelativeTo with null, the JDialog will be centered.

JDialog position relative to a JFrame

While that shows how you can center a JDialog, I think what you usually want to do is to positive your JDialog properly relative to a JFrame. To do that, you'll use code that looks like this:

// create your jdialog
JDialog d = new JDialog();

// tell the jvm you want to position the dialog relative
// to an exististing jframe
d.setLocationRelativeTo(myJFrame);

// display the jdialog
d.setVisible(true);

This doesn't exactly center the JDialog, but it does set the JDialog in a position to the JFrame. For more information on what this does, see the Javadoc for the setLocationRelativeTo method.

A complete JDialog center example

I usually like to share complete source code examples, so to that end, here's a complete Java class that shows how to display a JDialog relative to a JFrame.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JDialogCenterExample
{
  static JFrame frame;

  public static void main(String[] args)
  {
    // schedule this for the event dispatch thread (edt)
    SwingUtilities.invokeLater(new Runnable()
    {
      public void run()
      {
        displayJFrame();
      }
    });
  }

  static void displayJFrame()
  {
    frame = new JFrame("Our JDialog Center Example");

    // create our jbutton, then tell it what to do when
    // it is pressed
    JButton showDialogButton = new JButton("Show Dialog");
    showDialogButton.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        // display/center the jdialog when the button is pressed
        JDialog d = new JDialog(frame, "Hello", true);
        d.setLocationRelativeTo(frame);
        d.setVisible(true);
      }
    });

    // put the button on the frame
    frame.getContentPane().setLayout(new FlowLayout());
    frame.add(showDialogButton);

    // set up the jframe, then display it
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(300, 200));
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

Note that if you really want your JDialog centered, just change this line of code:

d.setLocationRelativeTo(frame);

to this:

d.setLocationRelativeTo(null);