Container myParent = msgDialog.getParent();
Point topLeft = myParent.getLocationOnScreen();
Dimension parentSize = myParent.getSize();
Dimension mySize = msgDialog.getSize();
int x, y;
if (parentSize.width > mySize.width)
x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
else
x = topLeft.x;
if (parentSize.height > mySize.height)
y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
else
y = topLeft.y;
msgDialog.setLocation(x, y);
要根据父窗口的大小和位置,再根据本dialog的大小来设置location才有效果
先设置 JDialog.setLayout(null);