[英]The application automatically adds 10 pixels to width and height
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.我的问题很奇怪,在搜索和阅读代码 40 次之后,我无法解释为什么 jpanel 和 jframe 的宽度和高度增加了 10 个像素。
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: startGame 方法中的 println 打印:
w 610, h 410
Thanks in advance.提前致谢。
使用frame.setUndecorated(true)
那么你就会明白为什么高度和宽度增加了 10pxls。
I just encountered this problem when trying to add a single custom JPanel to my JFrame, which acts as a canvas.我刚刚在尝试将单个自定义 JPanel 添加到我的 JFrame(充当画布)时遇到了这个问题。 I'm using Java 8 (update 231) and this is still an issue happened.我正在使用 Java 8(更新 231),这仍然是一个问题。
I don't exactly know why this is happening.我不完全知道为什么会这样。 In the end, the issue could be fixed by calling the frame.setResizable(false)
after frame.setVisible(true)
on the JFrame.最后,可以通过在 JFrame 上的frame.setVisible(true)
之后调用frame.setResizable(false)
来解决该问题。
Since I'm late to the party here, I hope this will help someone struggling with this as well.由于我在这里参加聚会迟到了,我希望这也能帮助那些为此苦苦挣扎的人。
Have a nice day祝你今天过得愉快
EDIT: Just saw the comments below the answer suggesting kind of the same by moving frame.setResizable(false)
before frame.pack()
, which works as well.编辑:刚刚看到答案下面的评论,通过在frame.setResizable(false)
之前移动frame.setResizable(false)
暗示类似的frame.pack()
,这也有效。 Sorry for bringing this up again.. :)很抱歉再次提出这个问题.. :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.