I am adding a bunch of JInternalFrame
s 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!
Work out the top-left corner of the new location (based on the size of the
JDesktopPane
andJInternalFrame
) and then callJInternalFrame.setLocation
.I would suggest the Window.setLocationRelativeTo(Component) method, which will center the window relative to a specified component. Instead of passing in a JDesktopPane, you might want to obtain the parent frame for a component, since otherwise, your JInternalFrame will be centered according to whichever component you pass in.
Here is a code sample:
If you are using Netbeans (which is recommended for desktop apps) you just need to:
Now you can set the for position as you wish :)
Add this void
and when adding the jInternalFrame call:
For reference, here is the solution I used, based on dogbane's advice: