2

My question is very wierd, after searching and reading the code 40 times, i can't explain why the jpanel and jframe gets additional 10 pixels to their width and height.

the code is:

public class Game extends JPanel implements Runnable {

        public static final String NAME = "ALPHA !";

        public static final int WIDTH = 600, HEIGHT = 400;

        public static void main(String[] args) {
            Game game = new Game();
            game.setMinimumSize(new Dimension(WIDTH, HEIGHT));
            game.setMaximumSize(new Dimension(WIDTH, HEIGHT));
            game.setPreferredSize(new Dimension(WIDTH, HEIGHT));
            game.setFocusable(true);
            game.requestFocusInWindow();

            JFrame frame = new JFrame(NAME);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            frame.setLayout(new BorderLayout());
            frame.add(game, BorderLayout.CENTER);
            frame.pack();

            frame.setResizable(false);
            frame.setAlwaysOnTop(true);
            frame.setLocationRelativeTo(null);

            frame.setVisible(true);
            game.startGame();
        }

        public void startGame() {
            System.out.println("w " + getWidth() + ", h " + getHeight());
            new Thread(this).start();
        }
}

The println in the startGame method prints:

w 610, h 410

Thanks in advance.

4

2 回答 2

0

使用 frame.setUndecorated(true)然后你就会明白为什么高度和宽度增加了10pxls。

于 2013-07-06T21:54:13.337 回答
0

我在尝试将单个自定义 JPanel 添加到充当画布的 JFrame 时遇到了这个问题。我正在使用 Java 8(更新 231),这仍然是一个问题。

我不完全知道为什么会这样。最后,可以通过在 JFrame 上调用frame.setResizable(false)after来解决问题。frame.setVisible(true)

由于我在这里参加聚会迟到了,我希望这也能帮助那些为此苦苦挣扎的人。

祝你今天过得愉快

编辑:刚刚看到答案下方的评论通过移动frame.setResizable(false)before暗示了相同的frame.pack()内容,这也有效。很抱歉再次提出这个问题.. :)

于 2019-11-13T18:24:14.693 回答