java 的JDialog设置了模态为真后怎么设置居中显示啊. 我用了setLocation()和setBounds()都不行啊

2025-01-06 19:28:41
推荐回答(2个)
回答1:

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才有效果

回答2:

先设置 JDialog.setLayout(null);