如何在屏幕中居中 JFrame

在我学徒之初,我问自己一个问题:我该如何把<屏幕中央的 i>窗口?我使用了 setLocationRelativeTo 并传递 null.

下面是一个展示这种技术的例子,setLocationRelativeTo(null) 方法在构造函数的末尾调用.

import java.awt.Dimension;
导入 java.awt.Toolkit;
导入 javax.swing.JFrame;

public class JFrame_center extends JFrame{

public static void main(String[] args) {

JFrame frame = new JFrame(JFrame center”);
frame.pack();

//检索屏幕尺寸
SizeScreen size = Toolkit.getDefaultToolkit().getScreenSize();
int height = screensize.height;
int width = sizeScreen.width;
//size 是长度和高度的一半
frame.setSize(width/2, height/2);

//这里我们居中我们的窗口
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Output
center

就是这样!我们的窗口在屏幕中央很好地对齐。在此程序中,该方法已被调用getScreenSize 类 java 工具包 检索运行程序的屏幕大小。此方法非常有效,因为它会根据用户的屏幕返回维度。

Reference
使用 SWING