我一直试图将jpanel的高度设置为窗口高度的80%。我做的每一种方式都会创建一个小矩形,或填充整个窗口。目前,这是我的代码;
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
window.setSize(xSize,ySize);
JPanel p = new JPanel();
p.setBackground(Color.PINK);
p.setLayout(new BorderLayout());
int gameHeight = (int)(Math.round(ySize * 100.0/window.getHeight()));
int gameWidth = (int)(Math.round(xSize * 100.0/window.getWidth()));
p.setPreferredSize(new Dimension(gameHeight, gameWidth));
p.add(new JLabel(" "));
window.add(p, BorderLayout.SOUTH);
答案 0 :(得分:6)
你的数学略有偏差。
要获取80%的值,您应该将其加倍0.80
,因此您希望面板高度为ySize * 0.80
,面板宽度为xSize * 0.80
。
int gameHeight = (int) (Math.round(ySize * 0.80));
int gameWidth = (int) (Math.round(xSize * 0.80));
p.setPreferredSize(new Dimension(gameWidth, gameHeight));