Java Swing How to - Vertical Align of GridBagLayout Panel on BorderLayout.CENTER








Question

We would like to know how to vertical Align of GridBagLayout Panel on BorderLayout.CENTER.

Answer

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
/*from  w  w w  .ja  v  a2 s . c  om*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame {

  public static void main(String arg[]) {
    JFrame frame = new JFrame();
    frame.setLayout(new BorderLayout());

    JPanel gb = new JPanel(new GridBagLayout());
    JLabel content = new JLabel("Some text");

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.NORTH;
    gbc.weighty = 1;

    gb.add(content, gbc); // gbc is containing the GridBagConstraints
    frame.add(gb, BorderLayout.CENTER);

    frame.setVisible(true);
  }

}