I am trying to learn GridBagLayout. I've gotten the hang of it in many respects, but I am having serious problems when the first row has element(s) with a gridwidth greater than 1 or the first column has elements(s) with a gridheight greater than 1. I'm trying to make a very simple GUI with only four elements, slightly staggered. I have attached images of what it should look like and what it actually looks like. The actual output has all the elements converging at a central point, which is not what I want. The code is below. Anyone see where I have gone wrong? Thanks.
import java.awt.*;
import javax.swing.*;
public class GridBagExperiment extends JFrame
{
JPanel redPanel, bluePanel, greenPanel, yellowPanel;
double redWidthPercent = 0.40;
double redHeightPercent = 0.40;
double blueWidthPercent = 0.60;
double blueHeightPercent = 0.40;
double greenWidthPercent = 0.60;
double greenHeightPercent = 0.60;
double yellowWidthPercent = 0.40;
double yellowHeightPercent = 0.60;
GridBagConstraints gbc;
Container container;
public static void main (String args[])
{
GridBagExperiment gbe = new GridBagExperiment ();
}
public GridBagExperiment ()
{
this.setSize (400, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = this.getContentPane();
redPanel = new JPanel ();
bluePanel = new JPanel ();
greenPanel = new JPanel ();
yellowPanel = new JPanel ();
redPanel.setBackground(Color.RED);
bluePanel.setBackground(Color.BLUE);
greenPanel.setBackground(Color.GREEN);
yellowPanel.setBackground(Color.YELLOW);
container.setLayout(new GridBagLayout ());
gbc = new GridBagConstraints ();
AddPanel (redPanel, 0, 0, 1, 1, redWidthPercent, redHeightPercent);
AddPanel (bluePanel, 1, 0, 2, 1, blueWidthPercent, blueHeightPercent);
AddPanel (greenPanel, 0, 1, 2, 1, greenWidthPercent, greenHeightPercent);
AddPanel (yellowPanel, 2, 1, 1, 1, yellowWidthPercent, yellowHeightPercent);
this.setVisible (true);
}
public void AddPanel (JPanel panel, int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty)
{
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.fill = GridBagConstraints.BOTH;
this.add (panel, gbc);
}
}