views:

61

answers:

3

I'm using Netbeans to develop 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? I've been struggling with this and with setting the default button the "enter" key is tied to.

Thanks!

+6  A: 
frame.setLocationRelativeTo( null );
camickr
Does that work also on older versions of Java ? I'm surprised because a while ago I figured out the only way to do that was "by hand", as explained here: http://www.java2s.com/Code/Java/Swing-JFC/Howtocenteraframeordialog.htm
Jules Olléon
That is valid as of 1.4, but you have to make sure that you pack or otherwise size the screen correctly first.
Yishai
Not really obvious when you don't know it, but the behavior of [setLocationRelativeTo()](http://tinyurl.com/34syhcj), with a null, is indeed to center the Window, as described in the javadoc.
Gnoupi
+1  A: 

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

Jules Olléon
A: 

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.

Taisin