import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /** a GUI application playing with GridLayout...! @author Sharon Tuttle @version 2021-10-05 */ public class GridLayoutPlay { /** creates a simple frame with a panel that includes some buttons laid out using GridLayout @param args not used here */ public static void main(String[] args) { EventQueue.invokeLater( () -> { GridLayoutPlayFrame mainFrame = new GridLayoutPlayFrame(); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setVisible(true); } ); } } /** A frame with a panel that includes buttons laid out using GridLayout */ class GridLayoutPlayFrame extends JFrame { // data fields private static final int DEFAULT_WIDTH = 600; private static final int DEFAULT_HEIGHT = 450; /** construct a GridLayoutPlayFrame instance */ public GridLayoutPlayFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setTitle("A Little GridLayout Play"); GridLayoutPlayPanel gPanel = new GridLayoutPlayPanel(); add(gPanel); } } /** A panel containing several elements laid out using GridLayout */ class GridLayoutPlayPanel extends JPanel { // data fields! private static final Font BIG_FONT = new Font("SanSerif", Font.PLAIN, 30); private static final Font HUGE_FONT = new Font("SanSerif", Font.PLAIN, 60); /** constructs a GridLayoutPlayPanel instance */ public GridLayoutPlayPanel() { int numRows = 4; int numCols = 5; GridLayout myGridLayout = new GridLayout(numRows, numCols); setLayout(myGridLayout); // let's make and instantiate an array of JButtons! JButton[] buttonArray = new JButton[20]; for (int i = 0; i < buttonArray.length; i++) { buttonArray[i] = new JButton("#" + (i+1) ); buttonArray[i].setFont(BIG_FONT); // giving one of the buttons comically-longer label text // to show that GridLayout keeps the "cells" in the grid // all the same size if (i == 4) { buttonArray[i].setText("MOOOOOOOOOOOOOOOOO"); } add(buttonArray[i]); } } }