Reputation: 3820
I am using grid layout in a frame and I want to put two panels in this frame in which one of them takes one third of the frame size and the other two third of the screen, how can I do that?
I have tried this but it didnot work for me:
code:
this.setLayout(new GridLayout(2, 1));
Dimension d2 = new Dimension(2*this.getHeight()/3, this.getWidth());
Dimension d3 = new Dimension(this.getHeight() / 3, this.getWidth());
panel1.setPreferredSize(d2);
panel1.setMaximumSize(d2);
panel1.setMinimumSize(d2);
panel2.setPreferredSize(d3);
panel2.setMaximumSize(d3);
panel2.setMinimumSize(d3);
this.add(panel1);
this.add(panel2);
thanks in advance.
Upvotes: 1
Views: 117
Reputation: 2920
GridLayout is not the right layout manager to use in this situation. GridLayout sets the width and height of all components in the container equal to each other. Attempting to set the preferred sizes of the components manually will have no effect since the layout manager takes care of that internally.
You can instead use GridBagLayout, and control the weight of the components using GridBagConstraints:
GridBagLayout layout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
this.setLayout(layout);
JPanel panel1 = new JPanel(), panel2 = new JPanel();
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.weightx = 1;
constraints.weighty = 1.0/3.0;
layout.setConstraints(panel1, constraints);
this.add(panel1);
constraints.weighty = 2.0/3.0;
layout.setConstraints(panel2, constraints);
this.add(panel2);
Upvotes: 2