How to set gridx and gridy values or cell number for a component - Java Swing

Java examples for Swing:GridBagLayout

Introduction

Setting gridx and gridy Properties for Components in a GridBagLayout

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

    for (int y = 0; y < 3; y++) {
      for (int x = 0; x < 3; x++) {
        gbc.gridx = x;/* www .  j av  a2s.  c  om*/
        gbc.gridy = y;
        String text = "Button (" + x + ", " + y + ")";
        contentPane.add(new JButton(text), gbc);
      }
    }
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials