我的问题非常奇怪,在搜索和读取代码40次之后,我无法解释为什么jpanel和jframe的宽度和高度额外增加10个像素。
代码是:
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();
}
}
startGame方法中的println打印:
w 610, h 410
提前感谢。
使用frame.setUndecorated(true)
,您将理解为什么高度和宽度增加10pxls。
我只是在尝试将单个自定义JPanel添加到用作画布的JFrame时遇到了此问题。我正在使用Java 8(更新231),但这仍然是一个问题。
我不完全知道为什么会这样。最后,可以通过在JFrame的frame.setResizable(false)
之后调用frame.setVisible(true)
来解决此问题。
由于我在这里参加聚会迟到,所以我希望这也会对与此相关的人有所帮助。
祝你有美好的一天