此外,如果你自己做,你需要考虑屏幕的插图,Toolkit.getScreenInsets
以考虑任务栏之类的东西,它可能位于任何屏幕边缘并且具有任何大小。
在我可以针对 Java 1.4 之前,我使用过:
static public void centerWindow(Window wnd, Component relcom) {
Rectangle scrbnd=getScreenBounds(wnd);
Dimension wndsiz=wnd.getSize();
Container root=null;
int px,py;
if(relcom!=null) {
if(relcom instanceof Window || relcom instanceof java.applet.Applet) {
root=(Container)relcom;
}
else {
Container parent;
for(parent=relcom.getParent(); parent!=null; parent=parent.getParent()) {
if(parent instanceof Window || parent instanceof java.applet.Applet) {
root=parent;
break;
}
}
}
}
if(relcom==null || !relcom.isShowing() || root==null || !root.isShowing()) {
px=(scrbnd.x+((scrbnd.width -wndsiz.width )/2));
py=(scrbnd.y+((scrbnd.height-wndsiz.height)/2));
}
else {
Point relloc=relcom.getLocationOnScreen();
Dimension relsiz=relcom.getSize();
px=(relloc.x+((relsiz.width -wndsiz.width )/2));
py=(relloc.y+((relsiz.height-wndsiz.height)/2));
}
if((px+wndsiz.width )>(scrbnd.x+scrbnd.width )) { px=((scrbnd.x+scrbnd.width )-wndsiz.width ); }
if((py+wndsiz.height)>(scrbnd.y+scrbnd.height)) { py=((scrbnd.y+scrbnd.height)-wndsiz.height); }
if(px<scrbnd.x) { px=scrbnd.x; }
if(py<scrbnd.y) { py=scrbnd.y; }
wnd.setLocation(px,py);
}