How do I open a JInternalFrame centered in a JDesktopPane?

孤街醉人 提交于 2019-11-30 20:33:13

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);

Work out the top-left corner of the new location (based on the size of the JDesktopPane and JInternalFrame) and then call JInternalFrame.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:

private void showDialog(Dialog dialogToCenter, Component button) {
    Frame frame = JOptionPane.getFrameForComponent(button);
    dialogToCenter.setLocationRelativeTo(frame);
    dialogToCenter.setVisible(true);
}

If you are using Netbeans (which is recommended for desktop apps) you just need to:

  1. Select the form, right click and then properties;
  2. Go to code tab;
  3. Change "Form size policy" from "Generate Pack()" to "Generate Resize Code";
  4. Form Position (option above Form size policy) will be available.

Now you can set the for position as you wish :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!