How do I open a JInternalFrame centered in a JDesktopPane?

Steven picture Steven · Sep 20, 2011 · Viewed 23.1k times · Source

I am adding a bunch of JInternalFrames into a JDesktopPane, as the user selects to open various features through the menus. But I would like the internal frames to open centered in the desktop pane, as opposed to the upper left, where they seem to default.

How can I specify that the JInternalFrames open centered, or move them to the center after opening?

jDesktopPane.add(jInternalFrame); // jInternalFrame is not centered!

Answer

Steven picture Steven · Sep 21, 2011

For reference, here is the solution I used, based on dogbane's advice:

Dimension desktopSize = desktopPane.getSize();
Dimension jInternalFrameSize = jInternalFrame.getSize();
jInternalFrame.setLocation((desktopSize.width - jInternalFrameSize.width)/2,
    (desktopSize.height- jInternalFrameSize.height)/2);