我正在开发一个Java Swing 应用程序。如何使得无论是该程序本身还是其他窗口,它们都能够在屏幕中央打开?
frame.setLocationRelativeTo( null );
frame.setLocationRelativeTo(null); 使窗口在中心位置打开。
祝好, Rehan Farooq
你需要手动使用 setLocation(x,y)
来完成它。
类似这样:
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((dim.width-frameWidth)/2, (dim.height-frameHeight)/2);
应该可以做到(未经测试)。
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)
,但是按钮必须已经添加到对话框中并且可见。