Center JDialog over parent

On the JDialog you’ve created you should call pack() first, then setLocationRelativeTo(parentFrame), and then setVisible(true). With that order the JDialog should appear centered on the parent frame.

If you don’t call pack() first, then setting the location relative to the parent doesn’t work properly because the JDialog doesn’t know what size it is at that point. It appears to take the size as 0 by 0, which results in the “top left pixel of the popup over the center pixel of the parent” positioning mentioned in a comment to one of the other answers.

Leave a Comment