Starting GridBagLayout from top left corner in Java Swing

Read the section from the Swing tutorial on How to Use GridBagLayout. The secton on "weightx,weighty" states:

Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container.


a quick and simple way:

add a blank JLabel to end of page:

    // your code goes here
    gbc.weightx = 1;
    gbc.weighty = 1;

    bg.add(new JLabel(" "), gbc);  // blank JLabel

For those, who use IDE (e.g. NetBeans), I finally found nice trick: if you want to add components to top and use their preferred sizes: add another empty panel with weighty = 1.0. Copied from auto-generated code (NetBeans):

gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weighty = 1.0;
jPanelOptions.add(jPanelFiller, gridBagConstraints);

You need to use your GridBagConstraints' anchor property. This should do it for you:

frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
frame.add(panel, gbc);

I'm not guaranteeing that you won't have to set other properties of the constraints object to get the layout you desire. In particular, you may need to set weightx and weighty to be 1 so that the panel takes up all of the available space given to it.