In the example below I have a JPanel with BoxLayout which contains another JPanel with GridBagLayout.
By adding a vertical glue I expect the contents of the inner panel to be "glued" to the top of the outer panel.
But I see the label "A" in the center. If I remove GridBagLayout, A is shown at the top. Why does this happen?
import javax.swing.*;
import java.awt.*;
public class Test {
public static void main(String[] args) {
JPanel contentPane = new JPanel();
JFrame frame = new JFrame();
frame.setContentPane(contentPane);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JPanel gridBagPanel = new JPanel();
gridBagPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.NONE;
gridBagPanel.add(new JLabel("A"), gbc);
contentPane.add(gridBagPanel);
contentPane.add(Box.createVerticalGlue());
frame.setSize(800, 200);
frame.setVisible(true);
}
}
Because the default value of the anchor
property of GridBagConstraints
is CENTER
. If there is more space in the inner panel than the preferred size of the JLabel, the JLabel would be centered with respect to the available space in the inner panel (since you set fill to NONE).
You can use the anchor value NORTHWEST
to glue the label to the top of the panel:
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weighty = 1;
gbc.weightx = 1;
You also need to set the weights per Java documentation: "Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container. This is because when the weight is 0.0 (the default), the GridBagLayout puts any extra space between its grid of cells and the edges of the container."