簡體   English   中英

setLocationRelativeTo(null)沒有使框架居中

[英]setLocationRelativeTo(null) is not centering the frame

我想將框架定位在屏幕的中央,但是當我鍵入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);

    }
}

當使用null作為參數調用setLocationRelativeTo()時,必須之前調用setSize() 否則,即使您的框架對於程序的其余部分(對您而言!)看起來像是一個500x400的窗口,對於setLocationRelativeTo()方法而言,它實際上看起來像是一個無量綱的點(窗口的左上角)。 ..它將居中,導致窗口顯示在右下角。

您要完成的工作應如下所示:

    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);

}

我的朋友,這一切都與秩序有關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM