This video explains how to use java.awt.GridLayout to arrange buttons in rows and columns. This will also show how to add padding between the grid of buttons.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
package AwtDemoPkg; import java.awt.Button; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class FrameWindow extends Frame implements WindowListener { public FrameWindow(String FrameTitle) { //Display the Frame Window super(FrameTitle); setSize(460, 170); setLocation(100,100); addWindowListener(this); //Sample 01: Create 5 Buttons Button btn1 = new Button("01"); Button btn2 = new Button("02"); Button btn3 = new Button("03"); Button btn4 = new Button("04"); Button btn5 = new Button("05"); Button btn6 = new Button("06"); //Sample 02: Set the Layout Manager setLayout(new GridLayout(2,3)); //Sample 03: Add All the Buttons add(btn1); add(btn2); add(btn3); add(btn4); add(btn5); add(btn6); } public void windowOpened(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowClosing(WindowEvent e) { this.dispose(); } } ============================================== //Replace Snippet 01-03 with the following //Sample 01: Set the Layout Manager GridLayout grdLayout = new GridLayout(5,10); setLayout(grdLayout); //Sample 02: Set Gap between rows & columns grdLayout.setHgap(6); grdLayout.setVgap(10); //Sample 03: Add Components for(int i=1; i<51; i++) { //3.1: Create the Buttons String btnCaption = Integer.toString(i); Button btn = new Button(btnCaption); add(btn); } |
Categories: AWT-Tube