import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /** * playing lightly with GridLayout * * @author Sharon Tuttle * @version 2015-09-29 */ public class GridLayoutPlay { /** * creates a frame for GridLayout play * * @param args not used here */ public static void main(String[] args) { EventQueue.invokeLater( new Runnable() { public void run() { GridLayoutPlayFrame aFrame = new GridLayoutPlayFrame(); aFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); aFrame.setVisible(true); } }); } } /** * a frame with some GridLayout play */ class GridLayoutPlayFrame extends JFrame { public static final int DEFAULT_WIDTH = 500; public static final int DEFAULT_HEIGHT = 350; /** * construct a GridLayoutPlay-panel frame instance */ public GridLayoutPlayFrame() { this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); this.setTitle("GridLayout Playing"); // create and add a GridLayoutPlay panel to my frame GridLayoutPlayPanel aGridLayoutPlayPanel = new GridLayoutPlayPanel(); this.add(aGridLayoutPlayPanel); } } /** * a panel with GridLayout playing */ class GridLayoutPlayPanel extends JPanel { // named constants for bigger fonts, and desired "grid" size private final static Font DISPLAY_FONT = new Font("Dialog", Font.PLAIN, 20); private final static Font HUGE_FONT = new Font("Dialog", Font.PLAIN, 60); private final static int NUM_ROWS = 4; private final static int NUM_COLS = 5; /** * construct a panel to play with GridLayout */ public GridLayoutPlayPanel() { // make this new panel use GridLayout // NOTE: checked Java 8 API after class -- if give number // of rows and number of columns in GridLayout's // constructor, and both are non-zero, // number of columns is IGNORED! "the number of // columns [in that case] is determined by // the specified number of rows and the total // number of components in the layout." !! // Also from the Java 8 API: // "Specifying the number of columns affects the // layout only when the number of rows is set to // zero"...! this.setLayout(new GridLayout(NUM_ROWS, NUM_COLS)); JButton[] buttonArray = new JButton[(NUM_ROWS * NUM_COLS) + 5]; // also from the Java 8 API: the container's // ComponentOrientation property determines // order components will be added to the grid -- // default for JPanel is evidently horizontal and // left to right; for (int i=0; i < buttonArray.length; i++) { buttonArray[i] = new JButton("#" + (i+1) ); buttonArray[i].setFont(DISPLAY_FONT); this.add(buttonArray[i]); } } }