ورود

View Full Version : سوال: متد setLocationRelativeTo چگونه کار می کند



svmone
جمعه 27 آذر 1394, 15:06 عصر
سلام
برای اینکه فرم رو وسط صفحه نمایش قرار بدم از این متد استفاده می کنم اما میخواستم بدونم چطور کار میکنه؟

this.setLocationRelativeTo(null);

persianshadow
دوشنبه 30 آذر 1394, 14:19 عصر
جاوا یه زبان کدباز هست و خب اینم کد این متد :). :




public void setLocationRelativeTo(Component c) {
// target location
int dx = 0, dy = 0;
// target GC
GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
Rectangle gcBounds = gc.getBounds();

Dimension windowSize = getSize();

// search a top-level of c
Window componentWindow = SunToolkit.getContainingWindow(c);
if ((c == null) || (componentWindow == null)) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gc = ge.getDefaultScreenDevice().getDefaultConfiguratio n();
gcBounds = gc.getBounds();
Point centerPoint = ge.getCenterPoint();
dx = centerPoint.x - windowSize.width / 2;
dy = centerPoint.y - windowSize.height / 2;
} else if (!c.isShowing()) {
gc = componentWindow.getGraphicsConfiguration();
gcBounds = gc.getBounds();
dx = gcBounds.x + (gcBounds.width - windowSize.width) / 2;
dy = gcBounds.y + (gcBounds.height - windowSize.height) / 2;
} else {
gc = componentWindow.getGraphicsConfiguration();
gcBounds = gc.getBounds();
Dimension compSize = c.getSize();
Point compLocation = c.getLocationOnScreen();
dx = compLocation.x + ((compSize.width - windowSize.width) / 2);
dy = compLocation.y + ((compSize.height - windowSize.height) / 2);

// Adjust for bottom edge being offscreen
if (dy + windowSize.height > gcBounds.y + gcBounds.height) {
dy = gcBounds.y + gcBounds.height - windowSize.height;
if (compLocation.x - gcBounds.x + compSize.width / 2 < gcBounds.width / 2) {
dx = compLocation.x + compSize.width;
} else {
dx = compLocation.x - windowSize.width;
}
}
}

// Avoid being placed off the edge of the screen:
// bottom
if (dy + windowSize.height > gcBounds.y + gcBounds.height) {
dy = gcBounds.y + gcBounds.height - windowSize.height;
}
// top
if (dy < gcBounds.y) {
dy = gcBounds.y;
}
// right
if (dx + windowSize.width > gcBounds.x + gcBounds.width) {
dx = gcBounds.x + gcBounds.width - windowSize.width;
}
// left
if (dx < gcBounds.x) {
dx = gcBounds.x;
}

setLocation(dx, dy);
}