Gridx and gridy Constraints for GridBagLayout - Java Swing

Java examples for Swing:GridBagLayout

Introduction

The gridx and gridy set the cell in the grid in which the component is placed.

A component can occupy multiple cells horizontally as well as vertically.

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();

    JButton b1 = new JButton("Button 1");
    JButton b2 = new JButton("Button 2");
    JButton b3 = new JButton("Button 3");

    gbc.gridx = 0;/*www  .j av  a2 s  .  com*/
    gbc.gridy = 0;
    frame.add(b1, gbc);

    gbc.gridx = 0;
    gbc.gridy = GridBagConstraints.RELATIVE;
    frame.add(b2, gbc);

    gbc.gridx = 1;
    gbc.gridy = GridBagConstraints.RELATIVE;
    frame.add(b3, gbc);
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials