【发布时间】:2016-11-12 04:50:31
【问题描述】:
我对 JPanel 和 JFrame 很陌生,可能没有按照我应该的方式使用它们。我正在尝试创建 Pong 游戏,在创建 JFrame 并向其中添加 JPanel 之后,我可以调整 JPanel 的大小,但我不知道如何调整 JFrame 的大小以适应它。游戏类扩展了 JPanel。
主要:
public static void main(String[] args) throws InterruptedException {
int height = 500, width =(int) (height*1.56); //height = 500, width = 780;
JFrame frame = new JFrame("Pong");
Game game = new Game();
frame.add(game);
frame.setVisible(true);
game.setSize(width, height);
System.out.println(game.getHeight());
System.out.println(game.getWidth());
game.setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println(frame.getHeight());
System.out.println(frame.getWidth());
}
输出:
500
780
39
136
输出应该是这样的:
500
780
*above* 500
*above* 780
编辑:
public static void main(String[] args) throws InterruptedException {
int height = 500, width =(int) (height*1.56); //height = 500, width = 780;
JFrame frame = new JFrame("Pong");
Game game = new Game();
frame.add(game);
frame.setVisible(true);
game.setPreferredSize(new Dimension(width, height));
frame.pack();
System.out.println(game.getHeight());
System.out.println(game.getWidth());
game.setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println(frame.getHeight());
System.out.println(frame.getWidth());
}
将 setSize 更改为 setPreferredSize,然后为 JFrame 调用 pack() 即可解决所有问题。
【问题讨论】:
-
添加所有组件后在 JFrame 上调用
pack()。也不要设置大小,而是处理首选大小(preferredSize)。 -
我明白了,谢谢!互联网上没有任何简单的答案,而你有她。