I would like to create a layout: 2 rows, 1 column. 1st row should occupy 70% height of the window and 2nd row 30% of the window. I achieve this by using weighty
attribute of GridBagConstraints
.
However I have problem with the width of my component, because when I resize application window the component remain in the center, its width is constant and I get a white spaces in the left and right of the component (even if I set fill
to BOTH
). This problem does not occur when I change the height of the window (components resize very well and fill full height of the window).
Below my constraints:
firstConstraints.gridx = 0;
firstConstraints.gridy = 0;
firstConstraints.weighty = 0.7;
firstConstraints.fill = GridBagConstraints.BOTH;
secondConstraints.gridx = 0;
secondConstraints.gridy = 1;
secondConstraints.weighty = 0.3;
secondConstraints.fill = GridBagConstraints.BOTH;
I think you also need:
gbc.weightx = 1.0;
See the secton from the Swing tutorial on How to Use a GrigBagLayout that talks about the weightx, weighty constraints.
simple example
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderPanels extends JFrame {
private static final long serialVersionUID = 1L;
public BorderPanels() {
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JPanel panel1 = new JPanel();
Border eBorder = BorderFactory.createEtchedBorder();
panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "70pct"));
gbc.gridx = gbc.gridy = 0;
gbc.gridwidth = gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = gbc.weighty = 70;
getContentPane().add(panel1, gbc);
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "30pct"));
gbc.gridy = 1;
gbc.weightx = 30;
gbc.weighty = 30;
gbc.insets = new Insets(2, 2, 2, 2);
getContentPane().add(panel2, gbc);
pack();
}
public static void main(String[] args) {
new BorderPanels().setVisible(true);
}
}