Java Swing How to - Position component at the top of the grid cell with GridBagLayout








Question

We would like to know how to position component at the top of the grid cell with GridBagLayout.

Answer

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
//from w  w  w  . ja v a  2s.  c  o  m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame dialog = new JFrame();
    dialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    dialog.setResizable(true); 

    JPanel guiHolder = new JPanel();
    guiHolder.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.PAGE_START;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    guiHolder.add(new JLabel("my test"), gbc);

    dialog.add(guiHolder);
    dialog.setSize(new Dimension(320, 240));
    dialog.setVisible(true);
  }
}