我想将框架放置在屏幕中央,但是当我输入 f.setLocationRelativeTo(null) 时。它将其定位到右下角。代码有问题吗?如果是这样,我该如何更改它以使框架居中?
public class Maze {
public static void main(String[] args) {
new Maze();
}
public Maze(){
JFrame f = new JFrame();
f.setTitle("Maze Game");
//f.add(new board());
f.setLocationRelativeTo(null);
f.setSize(500, 400);
f.setVisible(true);
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
当你用setLocationRelativeTo()
withnull
作为参数调用时,你必须在它setSize()
之前调用。否则,即使您的框架对于程序的其余部分(以及您!)来说可能看起来像一个 500x400 的窗口,但对于该setLocationRelativeTo()
方法来说,它本质上看起来像一个无量纲点(窗口的左上角)......是它将居中的位置,导致窗口出现在右下角。