I'm having an issue when using GridBagLayout, everything seems to be working as intended but there's a small gap at the bottom of the JFrame that I can't seem to get rid of.
This is the code I'm running...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private JFrame frame;
private JPanel container, header, content, footer;
public Test(){
frame = new JFrame();
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints gbc = new GridBagConstraints();
container = new JPanel();
container.setBackground(Color.blue);
container.setLayout(new GridBagLayout());
header = new JPanel();
header.setBackground(Color.red);
header.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
header.add(new JButton("Test"));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.BOTH;
container.add(header, gbc);
content = new JPanel();
content.setBackground(Color.green);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 0.9;
gbc.fill = GridBagConstraints.BOTH;
container.add(content, gbc);
footer = new JPanel();
footer.setBackground(Color.gray);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.BOTH;
container.add(footer, gbc);
frame.getContentPane().add(container);
frame.setMinimumSize(new Dimension(600,400));
}
public static void main(String[] args) {
Test main = new Test();
main.frame.pack();
main.frame.setVisible(true);
}
}
You'll notice there's about 2-3 pixels still showing at the bottom of UI, the background for the container is of course blue. This gap persists even when resizing. I'm guessing it has something to do with the GridBagConstraint weights as when I tried setting the weightY to equal values the problem resolves itself, but that obviously isn't what I want it to look like.
Take a look at the Relative Layout.
The layout has a property that allows you to control how to allocating extra pixels due to rounding problems.
The basic code could be:
This will give you a better 90/10 relationship than a GridBagLayout. A GridBagLayout allocates the preferred space first and then does the 90/10 on the extra space, to you don't have a true 90/10 relationship.