Java AWT GridLayout class

Introduction

GridLayout lays out components in a two-dimensional grid.

The constructors supported by GridLayout are shown here:

GridLayout()  
GridLayout(int numRows, int numColumns)  
GridLayout(int numRows, int numColumns, int horz, int vert) 
import java.awt.Font;
import java.awt.GridLayout;

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

class Demo extends JPanel {
  int n = 4;// w ww .  j  a va 2  s. c  o m
  public Demo() {
    setLayout(new GridLayout(n, n));
    setFont(new Font("SansSerif", Font.BOLD, 24));
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        int k = i * n + j;
        if (k > 0)
          add(new JButton("" + k));
      }
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Demo panel = new Demo();

    JFrame application = new JFrame();

    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    application.add(panel);
    application.setSize(250, 250);
    application.setVisible(true);
  }
}
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;

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

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("GridLayout Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(2,2));

    for (int i = 1; i <= 4; i++) {
      buttonPanel.add(new JButton("Button " + i));
    }/*from w ww .  j  a v a 2  s .  c  o m*/

    contentPane.add(buttonPanel, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}



PreviousNext

Related