Java 获取屏幕大小并将窗口居中显示
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();用来获取窗口大小
screenSize.width为窗口宽度,screenSize.height为窗口高度。
效果如下:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class WindowCenter {
public static void main(String[] args) {
// 定义窗口宽高常量
final int width = 430;
final int height = 360;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JFrame myJFrame = new JFrame("Java窗口居中显示");
// 设置窗口大小
myJFrame.setSize(width, height);
// 设置窗口居中显示
myJFrame.setLocation(screenSize.width / 2 - width / 2,
screenSize.height / 2 - height / 2);
//设置窗口可见
myJFrame.setVisible(true);
}
}