The fill Constraint for GridBagLayout - Java Swing

Java examples for Swing:GridBagLayout

Introduction

GridBagLayout sets the preferred width and height to each component.

The width of a column is decided by the widest component in the column.

The height of a row is decided by the highest component in the row.

fill property value sets how a component is expanded horizontally and vertically when its display area is bigger than its size.

fill constraint is only used when the component's size is smaller than its display area.

fill constraint has four possible values: NONE, HORIZONTAL, VERTICAL, and BOTH.

Its default value is NONE, which means "do not expand the component."

HORIZONTAL means "expand the component horizontally to fill its display area."

VERTICAL means "expand the component vertically to fill its display area."

BOTH means "expand the component horizontally and vertically to fill its display area."

Demo Code

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("GridBagLayout");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();

    gbc.gridx = 0; gbc.gridy = 0;// ww w  . j a v  a2  s .c  om
    frame.add(new JButton("Button 1"), gbc);
    gbc.gridx = 1; gbc.gridy = 0;
    frame.add(new JButton("Button 2"), gbc);
    gbc.gridx = 2; gbc.gridy = 0;
    frame.add(new JButton("Button 3"), gbc);

    gbc.gridx = 0; gbc.gridy = 1;
    frame.add(new JButton("Button 4"), gbc);
    gbc.gridx = 1; gbc.gridy = 1;
    frame.add(new JButton("This is a big Button 5"), gbc);
    gbc.gridx = 2; gbc.gridy = 1;
    frame.add(new JButton("Button 6"), gbc);

    gbc.gridx = 0; gbc.gridy = 2;
    frame.add(new JButton("Button 7"), gbc);
    gbc.gridx = 1; gbc.gridy = 2;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    frame.add(new JButton("Button 8"), gbc);
    gbc.gridx = 2; gbc.gridy = 2;
    gbc.fill = GridBagConstraints.NONE;
    frame.add(new JButton("Button 9"), gbc);
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials