GridLayout as Layout Manager in Java
So, now let’s start this tutorial!
1. Open JCreator or NetBeans and make a java program with a file name of gridLayout.java.
2. Import the following packages:
import java.awt.*; //used to access of GridLayout class import javax.swing.*; //used to access the JFrame and JButton class
3. Initialize your variable in your Main, variable frame for JFrame, and 6 buttons namely b1,b2,b3,b4,b5, and b6 as JButton.
JFrame frame = new JFrame("GridLayout as Layout Manager"); JButton b1, b2, b3, b4, b5, b6; b1 = new JButton("Button1"); b2 = new JButton("Button2"); b3 = new JButton("Button3"); b4 = new JButton("Button4"); b5 = new JButton("Button5"); b6 = new JButton("Button6");
4. To have a GridLayout as the layout manager, we will use the setLayout method of the frame.
frame.getContentPane().setLayout(new GridLayout(2,3));
As you can see there are two parameters of GridLayout class. The 2 indicates the number of rows and the 3 indicates the column of the grid.
When we create a GridLayout object, you indicate the number of rows and columns, and the container will be divided into that grid accordingly.
Then add the buttons into the frame using the add method.
frame.getContentPane().add(b1); frame.getContentPane().add(b2); frame.getContentPane().add(b3); frame.getContentPane().add(b4); frame.getContentPane().add(b5); frame.getContentPane().add(b6);
5. Lastly, set the size, visibility, and the close operation of the frame. Have this code below:
frame.setSize(500, 400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Output:
Here’s the full code of this tutorial:
import java.awt.*; //used to access of GridLayout class import javax.swing.*; //used to access the JFrame and JButton class public class gridLayout{ public static void main(String[] args) { JFrame frame = new JFrame("GridLayout as Layout Manager"); JButton b1, b2, b3, b4, b5, b6; b1 = new JButton("Button1"); b2 = new JButton("Button2"); b3 = new JButton("Button3"); b4 = new JButton("Button4"); b5 = new JButton("Button5"); b6 = new JButton("Button6"); frame.getContentPane().setLayout(new GridLayout(2,3)); frame.getContentPane().add(b1); frame.getContentPane().add(b2); frame.getContentPane().add(b3); frame.getContentPane().add(b4); frame.getContentPane().add(b5); frame.getContentPane().add(b6); frame.setSize(500, 400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }