2010-06-21 36 views
17

我正在开发Java Swing应用程序。我该如何做到这一点,以便当程序本身和其他窗口打开时,它们会出现在屏幕的中心?中心摆动窗口

回答

47
frame.setLocationRelativeTo(null); 
+0

这是否也适用于旧版本的Java?我很惊讶,因为前一段时间我想通过“手工”来解决这个问题的唯一方法就是这样解释:http://www.java2s.com/Code/Java/Swing-JFC/Howtocenteraframeordialog.htm – 2010-06-21 03:55:53

+1

从1.4开始有效,但您必须确保您先正确包装或以其他方式确定屏幕的大小。 – Yishai 2010-06-21 04:09:54

+2

当你不知道它时,并不是很明显,但[setLocationRelativeTo()](http://tinyurl.com/34syhcj)的行为,其实是一个null,实际上是将该窗口居中,如javadoc中所述。 – Gnoupi 2010-06-21 08:16:16

1

您必须手动使用setLocation(x,y)

喜欢的东西:

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
frame.setLocation((dim.width-frameWidth)/2, (dim.height-frameHeight)/2); 

应该这样做(未测试)。

1

在多屏幕环境做手工给出这样的事情(静态的,因为你可能会想它一个实用工具类):

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

} 

至于默认按钮,它的JDialog.getRootPane().setDefaultButton(btn),但按钮必须已经添加到对话框中,并且可见。

+0

我在这里使用两台显示器。一个甚至是垂直移位。 camickr/Rehans的答案适合我。它将窗口置于第一个屏幕上。这不是你的方法试图完成的吗?或者我在这里错过了什么?谢谢! – Riscie 2014-02-01 19:04:23

+0

@Riscie不是真的。我的方法是试图找到你的组件显示在哪个屏幕上,所以你可以将它居中在这个屏幕上,而不仅仅是在第一个屏幕上。 – Taisin 2014-02-05 09:14:31

+0

感谢澄清!那么这很需要!遗憾的是,这不是默认提供的! – Riscie 2014-02-06 11:54:30

4

frame.setLocationRelativeTo(null);使框架在cetner

问候,开放 热汗法鲁克

+0

为我工作!谢谢! – StiGMaT 2015-01-18 05:29:59

3

这是很容易,如果你使用的是NetBeans。 在属性窗口的JFrame去“代码”选项卡。有一个选项为“生成中心”。检查该选项。 JFrame将显示在中心。