GridLayout
java.awt.GridLayout is the Layout which divides component area into a Grid of specified rows and cols. GridLayout can be useful in case when we need equal sub parts of a component ares. It re sizes the components added in it. Component add sequence plays an important role when we have set GridLayout. To set any layout of any component the method which can be used is: componetObject.setLayout(layoutManagerObject);
GridLayout Constructors
-
GridLayout()
This constructor creates one column for each component we add. Only 1 row will be created.
-
GridLayout(int rows, int cols)
This constructor creates specified number of rows and columns.
-
GridLayout(int rows, int cols, int hgap, int vgap)
This constructor creates specified number of rows and columns plus sets the given horizontal and vertical space between components.
As discussed in the above constructor summary, We have a constructor which takes rows and columns value as integers. Here the constrain/characteristic is: GridLayout is rigid about row creation. and It’s flexible in terms of column creation. For example, If we ask GridLayout to create 20 rows and 20 columns for us and we add only 3 components in Grid. In that case: It automatically understands our requirement and create 20 rows(Its for sure!) and 1 column only(Its Flexible!). Because 20 rows can accommodate our all components. In case we add 21 components, it will create 2 columns.
GridLayout with 2 rows and 2 columns
Program:
import java.applet.*; import java.awt.*; public class GridLayoutDemo extends Applet { Button b1, b2, b3; public void init() { GridLayout gl = new GridLayout(2,2); setLayout(gl); b1 = new Button("Button1"); b2 = new Button("Button2"); b3 = new Button("Button3"); add(b1); add(b2); add(b3); } } /* <applet code="GridLayoutDemo" width="500" height="200"></applet> */
Output:
GridLayout with 20 rows 20 columns
Program:
import java.applet.*; import java.awt.*; public class GridLayout20Demo extends Applet { Button b1, b2, b3; public void init() { GridLayout gl = new GridLayout(20,20); setLayout(gl); b1 = new Button("Button1"); b2 = new Button("Button2"); b3 = new Button("Button3"); add(b1); add(b2); add(b3); } } /* <applet code="GridLayout20Demo" width="500" height="500"></applet> */
Output:
Recent Comments