Reputation: 928
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!
Upvotes: 8
Views: 25366
Reputation: 195
this Align in Event ... don't forget
enter code here
private void jMenuItem_nuevo_usuarioActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
UsuariosJInternalFrame internalUsuario = new UsuariosJInternalFrame();
jDesktopPane_menu.add(internalUsuario);
Dimension desktopSize = jDesktopPane_menu.getSize();
Dimension FrameSize = internalUsuario.getSize();
internalUsuario.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2);
internalUsuario.setVisible(true);
}
Upvotes: 0
Reputation: 173
Add this void
public void addCentered(Component jif) {
desktopPane.add(jif);
jif.setLocation((desktopPane.getWidth()-jif.getWidth())/2, (desktopPane.getHeight()-jif.getHeight())/2);
jif.setVisible(true);
}
and when adding the jInternalFrame call:
addCentered(jifName);
Upvotes: 0
Reputation: 80
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 :)
Upvotes: 1
Reputation: 928
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);
Upvotes: 16
Reputation: 2113
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);
}
Upvotes: 0
Reputation: 274788
Work out the top-left corner of the new location (based on the size of the JDesktopPane
and JInternalFrame
) and then call JInternalFrame.setLocation
.
Upvotes: 4