Why does GridBagLayout center my components instead of putting it in the corner?

Cratylus picture Cratylus · Sep 1, 2011 · Viewed 25.5k times · Source

So far I managed to avoid using the GridBagLayout (by hand code) as much as possible, but I could not avoid it this time and I am reading the SUN's tutorial GridBagLayout So far it is not going well. I think I am missunderstanding something.
For example I try the following code (similar to the one in SUN's post):

public class MainFrame extends JFrame { 


    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setBounds(100, 100, 500, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container mainContainer = getContentPane();

        mainContainer.setLayout(new GridBagLayout());       

        //add label
        JLabel someLabel = new JLabel("Label 1:");
        GridBagConstraints constraints = new GridBagConstraints();

        constraints.gridx = 0;
        constraints.gridy = 0;
        //constraints.anchor = GridBagConstraints.FIRST_LINE_START;
        //constraints.weightx = 0.5;
        mainContainer.add(someLabel, constraints);      

        JTextField someText = new JTextField(30);

        constraints = new GridBagConstraints();

        constraints.gridx = 1;
        constraints.gridy = 0;
        constraints.weightx = 0.5;
        mainContainer.add(someText, constraints);

        //
    }

}

I get the label and the textfield one next to the other in the center of the frame.
But I was expecting that they would show up in the top left corner since the gridx and gridy is 0 for the label.
Even if I set constraints.anchor = GridBagConstraints.FIRST_LINE_START; still the same result.
Am I wrong here?
From the SUN's post:

Specify the row and column at the upper left of the component. The leftmost column has address gridx=0 and the top row has address gridy=0.

Answer

BenCole picture BenCole · Sep 1, 2011

Add constraints.weighty = 1; to the JLabel constraints and constraints.anchor = GridBagConstraints.NORTHWEST; to the TextField constraints.

EDIT:

From Oracle's GridBagLayout guide:

Larger numbers indicate that the component's row or column should get more space. For each column, the weight is related to the highest weightx specified for a component within that column, with each multicolumn component's weight being split somehow between the columns the component is in. Similarly, each row's weight is related to the highest weighty specified for a component within that row. Extra space tends to go toward the rightmost column and bottom row.