Stefano Maglione
Stefano Maglione

Reputation: 4150

Component size in JPanel

I've created a frame with inside two JPanel objects. This panel doesn't occupy all the space in a frame but only a part. I need they occupy equally the available space inside frame.

container = frame.getContentPane();
matricepc = new JPanel();
matrice = new JPanel();
matrice.setLayout(new GridLayout(griglia.getRow(), griglia.getColumn()));
matricepc.setLayout(new GridLayout(griglia.getRow(), griglia.getColumn()));
container.add(matricepc,BorderLayout.NORTH);
container.add(matrice,BorderLayout.SOUTH);

enter image description here

Upvotes: 0

Views: 49

Answers (1)

Marco13
Marco13

Reputation: 54611

container.setLayout(new GridLayout(0,1));
container.add(matricepc);
container.add(matrice);

EDIT: This ´GridLayout´ constructor expects two parameters: The first one is the number of rows, and the second one is the number of columns. When either of them is 0, then the respective number will be chosen based on the other one, and the number of components that are added. In this example: You specify that you want 1 column (and the number of rows does not matter - but since you add 2 components, the number of rows will be 2 - thus, you could also have written new GridLayout(2, 1).

EDIT2: Not really related to the original question, but more or less a general hint: Don't underestimate the power of nesting in order to achieve a particular layout. In this case, you can give

  • A BorderLayout to the main container (the content pane)
  • A GridLayout to a new panel that only contains the matrix-panels

and put the 'panelForMatrices' into the main container:

container.setLayout(new BorderLayout());

JPanel panelForMatrices = new JPanel(new GridLayout(0,1));
panelForMatrices.add(matricepc);
panelForMatrices.add(matrice);
container.add(panelForMatrices, BorderLayout.CENTER);

JPanel lateralPanel = ...
container.add(lateralPanel, BorderLayout.EAST);

Upvotes: 2

Related Questions