Java Set JPanel height to percentage of window height

I am trying to set the height of a jpanel to 80% of the window height. Each way I do it either creates a small rectangle or fills the whole window. This is currently 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);

      

+3


source to share


1 answer


Your math is a little off.

To get 80% of the value, you have to increase it by 0.80

, so you need the panel's height to ySize * 0.80

be and the panel's width to 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));

      

+5


source







All Articles