下面的示例将一个框架居中放在屏幕上:
package com.zetcode;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import javax.swing.JFrame;
public class CenterOnScreen extends JFrame {
public CenterOnScreen() {
initUI();
}
private void initUI() {
setSize(250, 200);
centerFrame();
setTitle("Center");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void centerFrame() {
Dimension windowSize = getSize();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Point centerPoint = ge.getCenterPoint();
int dx = centerPoint.x - windowSize.width / 2;
int dy = centerPoint.y - windowSize.height / 2;
setLocation(dx, dy);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
CenterOnScreen ex = new CenterOnScreen();
ex.setVisible(true);
}
});
}
}
为了在屏幕上居中显示帧,我们需要获取本地图形环境。从这个环境,我们确定中心点。结合框架尺寸,我们设法将框架居中。是将框架移动到中心位置的方法。setLocation()
请注意,这实际上是这样做的:setLocationRelativeTo(null)
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().getDefaultConfiguration();
gcBounds = gc.getBounds();
Point centerPoint = ge.getCenterPoint();
dx = centerPoint.x - windowSize.width / 2;
dy = centerPoint.y - windowSize.height / 2;
}
...
setLocation(dx, dy);
}