VOOZH about

URL: https://www.geeksforgeeks.org/java/java-awt-gridlayout-class/

⇱ Java AWT | GridLayout Class - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java AWT | GridLayout Class

Last Updated : 21 Aug, 2018
GridLayout class represents a layout manager with a specified number of rows and columns in a rectangular grid. The GridLayout container is divided into an equal-sized of rectangles, and one of the components is placed in each rectangle. Every rectangle cell has the same size therefore, they contain a component, which fills the entire cell. When the user changes or adjusts the size of the container, the size of each rectangles changes accordingly. Constructors of the class:
  1. GridLayout(): It Creates a grid layout with a default of one column per component, in a single row.
  2. GridLayout(int rw, int cl): It creates a grid layout with the specified number of rows and columns.
  3. GridLayout(int rw, int cl, int hgap, int vgap): It creates a grid layout with the specified number of rows and columns with horizontal and vertical gap.
Commonly Used Methods:
  • addLayoutComponent(String str, Component cmp): Adds the specified component with the specified name to the layout.
  • setColumns(int cl): Sets the number of columns in this layout to the specified value.
  • setHgap(int hgap): Sets the horizontal gap between components to the specified value.
  • setRows(int rw): Sets the number of rows in this layout to the specified value.
  • setVgap(int vgap): Sets the vertical gap between components to the specified value.
  • layoutContainer(Container pr): Lays out the specified container using this layout.
  • toString(): Returns the string representation of this grid layout's values.
Below programs illustrate the GridLayout class:
  • Program 1: In below program we are passing the argument in GridLayout. We create 4 JLabel components named "one", "two", "three", "four" and create 2 JButton components named "buttonsave" and "buttonexit" and create 4 Jtextfield components named "tname", "tcode", "tdesig", "tsalary" and all of add them to the JFrame by the method add(). We will set the visibility and size of the frame by using setVisible() and setSize() method. The layout is set by using setLayout() method. Output:

  • Program 2: In below program we are passing the argument in GridLayout. We create 5 JButton components named "btn1", "btn2", "btn3", "btn4", "btn5" and then add them to the JFrame by the method add(). We will set the visibility and size of the frame by using setvisible() and setsize() method. The layout is set by using setLayout() method.
Output:

Note: The above programs might not run in an online IDE. Please use an offline compiler. Reference: https://docs.oracle.com/javase/7/docs/api/java/awt/GridLayout.html
Comment
Article Tags:
Article Tags: