如何将JDialog定位在屏幕的中心?
发布于 2008-10-17 18:27:28
在Java 1.4+中,您可以这样做:
final JDialog d = new JDialog();
d.setSize(200,200);
d.setLocationRelativeTo(null);
d.setVisible(true);
或者(1.4之前的版本):
final JDialog d = new JDialog();
d.setSize(200, 200);
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Dimension screenSize = toolkit.getScreenSize();
final int x = (screenSize.width - d.getWidth()) / 2;
final int y = (screenSize.height - d.getHeight()) / 2;
d.setLocation(x, y);
d.setVisible(true);
发布于 2013-04-10 21:06:42
在pack()
方法之后使用下面这一行:
setLocation((Toolkit.getDefaultToolkit().getScreenSize().width)/2 - getWidth()/2, (Toolkit.getDefaultToolkit().getScreenSize().height)/2 - getHeight()/2);
发布于 2012-03-06 12:30:28
两个辅助对象,用于在屏幕或父对象内居中。
// Center on screen ( absolute true/false (exact center or 25% upper left) )
public void centerOnScreen(final Component c, final boolean absolute) {
final int width = c.getWidth();
final int height = c.getHeight();
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screenSize.width / 2) - (width / 2);
int y = (screenSize.height / 2) - (height / 2);
if (!absolute) {
x /= 2;
y /= 2;
}
c.setLocation(x, y);
}
// Center on parent ( absolute true/false (exact center or 25% upper left) )
public void centerOnParent(final Window child, final boolean absolute) {
child.pack();
boolean useChildsOwner = child.getOwner() != null ? ((child.getOwner() instanceof JFrame) || (child.getOwner() instanceof JDialog)) : false;
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final Dimension parentSize = useChildsOwner ? child.getOwner().getSize() : screenSize ;
final Point parentLocationOnScreen = useChildsOwner ? child.getOwner().getLocationOnScreen() : new Point(0,0) ;
final Dimension childSize = child.getSize();
childSize.width = Math.min(childSize.width, screenSize.width);
childSize.height = Math.min(childSize.height, screenSize.height);
child.setSize(childSize);
int x;
int y;
if ((child.getOwner() != null) && child.getOwner().isShowing()) {
x = (parentSize.width - childSize.width) / 2;
y = (parentSize.height - childSize.height) / 2;
x += parentLocationOnScreen.x;
y += parentLocationOnScreen.y;
} else {
x = (screenSize.width - childSize.width) / 2;
y = (screenSize.height - childSize.height) / 2;
}
if (!absolute) {
x /= 2;
y /= 2;
}
child.setLocation(x, y);
}
https://stackoverflow.com/questions/213266
复制相似问题