我是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()将其全部修复。
答案 0 :(得分:2)
再次,处理首选尺寸并确保在添加组件后在您的JFrame 上调用PeriodIndex
。此外,最好覆盖getPreferredSize而不是调用pack()
。例如:
setPreferredSize