Center JDialog over parent

Chris Drappier picture Chris Drappier · Apr 5, 2012 · Viewed 46.3k times · Source

I have a Java swing application with a button that produces a popup window when a certain action is performed. I'd like to align the center point of the popup window with the center point of the parent window when it is rendered. How can I calculate the x,y coordinates to plug into setLocation() for the popup window?

Just to clarify. I do not want the behavior of setLocationRelativeTo() because that sets the top-left pixel of the popup over the center pixel of the parent frame. I want to set the center pixel of the popup over the center pixel of the parent frame.

Answer

MB. picture MB. · May 14, 2012

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.