I've been trying to set a jpanel's height to 80% of the window's height. Every way I do it creates either a small rectangle, or fills the whole window. Currently, this is my code;
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);
Your math is slightly off.
To acquire 80% of a value, you should multiple it by 0.80
, so you would want the panel height to be ySize * 0.80
and the panel width to be 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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.