setLocationRelativeTo(null) 未使框架居中

问题描述 投票:0回答:3

我想将框架定位在屏幕中央,但是当我输入 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);

    }
}
java swing jframe frame
3个回答
6
投票

当您以

setLocationRelativeTo()
作为参数调用
null
时,您必须在
之前调用 
setSize() 。 否则,即使您的框架对于程序的其余部分(以及您!)来说可能看起来像一个 500x400 的窗口,但对于
setLocationRelativeTo()
方法来说,它本质上看起来像一个无量纲点(窗口的左上角)。 ..这就是它将居中的位置,导致窗口出现在右下角。


0
投票

您想要完成的任务应该如下所示:

    public static void main(String[] args) {
    new Maze();
}

public Maze(){
    JFrame f = new JFrame();
    f.setTitle("Maze Game");
    f.add(new board());
        //Notice I took out your comment over f.add to show the f.pack() method and where
        //your 'setLocationRelativeTo(null); statement should go in terms of it.
    f.setSize(500, 400);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //NOTICE! I changed the above line from (f.EXIT_ON_CLOSE) to (JFrame.EXIT_ON_CLOSE)
        // DO NOT LOOK OVER THAT!
    f.pack();
    f.setLocaitonRelativeTo(null);

}

一切都与秩序有关,我的朋友。


0
投票

导入 javax.swing.JFrame;

公开课迷宫{

public static void main(String[] args) {
    new Maze();
}

public Maze(){
    JFrame f = new JFrame();
    f.setTitle("Maze Game");
    f.setSize(500, 400);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);

}

}

© www.soinside.com 2019 - 2024. All rights reserved.