Center a Frame/Dialog
// centers the dialog within the screen [1.1]
// (put that in the Frame/Dialog class)
public void centerScreen() {
Dimension dim = getToolkit().getScreenSize();
Rectangle abounds = getBounds();
setLocation((dim.width - abounds.width) / 2,
(dim.height - abounds.height) / 2);
super.setVsible(true);
requestFocus();
}
// centers the dialog within the parent container [1.1]
// (put that in the Dialog class)
public void centerParent () {
int x;
int y; // Find out our parent
Container myParent = getParent();
Point topLeft = myParent.getLocationOnScreen();
Dimension parentSize = myParent.getSize(); Dimension mySize = getSize(); 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;
setLocation (x, y);
super.setVsible(true);
requestFocus();
}
New with JDK1.4, JDialog has method setLocationRelativeTo(parentComponent)
to position a JDialog relative to a parent. For a JWindow or a JFrame with no parent, then JFrame f = new JFrame();
f.setSize(100,100);
f.setLocationRelativeTo(null);
// centers the dialog within the screen [1.1]
// (put that in the Frame/Dialog class)
public void centerScreen() {
Dimension dim = getToolkit().getScreenSize();
Rectangle abounds = getBounds();
setLocation((dim.width - abounds.width) / 2,
(dim.height - abounds.height) / 2);
super.setVsible(true);
requestFocus();
}
// centers the dialog within the parent container [1.1]
// (put that in the Dialog class)
public void centerParent () {
int x;
int y; // Find out our parent
Container myParent = getParent();
Point topLeft = myParent.getLocationOnScreen();
Dimension parentSize = myParent.getSize(); Dimension mySize = getSize(); 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;
setLocation (x, y);
super.setVsible(true);
requestFocus();
}
New with JDK1.4, JDialog has method setLocationRelativeTo(parentComponent)
to position a JDialog relative to a parent. For a JWindow or a JFrame with no parent, then JFrame f = new JFrame();
f.setSize(100,100);
f.setLocationRelativeTo(null);
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货