Reputation: 161
I'm developing a Java Swing application. How can I make it so that when the program itself and any other windows open they come up in the center of the screen?
Upvotes: 16
Views: 14084
Reputation: 43
It is easy if you are using Netbeans. In property window of JFrame go to "Code" tab.There is an option as "Generate center".Check that option. JFrame will display in center.
Upvotes: 3
Reputation: 51
frame.setLocationRelativeTo(null); make the frame open in cetner
Regards, Rehan Farooq
Upvotes: 4
Reputation: 491
Doing it by hand in multi-screen environment gives something like this (static, 'cause you probably would want it in a utility class):
public static Rectangle getScreenBounds(Component top){
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
if (top != null){
Rectangle bounds = top.getBounds();
int centerX = (int) bounds.getCenterX();
int centerY = (int) bounds.getCenterY();
for (GraphicsDevice device : gd){
GraphicsConfiguration gc = device.getDefaultConfiguration();
Rectangle r = gc.getBounds();
if (r.contains(centerX, centerY)){
return r;
}
}
}
return gd[0].getDefaultConfiguration().getBounds();
}
public void centerWindowOnScreen(Window windowToCenter){
Rectangle bounds = getScreenBounds(windowToCenter);
Point newPt = new Point(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
Dimension componentSize = windowToCenter.getSize();
newPt.x -= componentSize.width / 2;
newPt.y -= componentSize.height / 2;
windowToCenter.setLocation(newPt);
}
As for default button, it's JDialog.getRootPane().setDefaultButton(btn)
, but button has to be already added to the dialog, and visible.
Upvotes: 1
Reputation: 6888
You'll have to do it by hand, using setLocation(x,y)
.
Something like:
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((dim.width-frameWidth)/2, (dim.height-frameHeight)/2);
should do it (not tested).
Upvotes: 1