Java Swing GridLayout
GridLayout places components in a cell of a grid. Each cell has the same size, therefore, each component takes up the same space in a container. When the user adjusts the container, the size of each component changes accordingly.
Here are the constructors of the GridLayout class:
Constructors | Description |
---|---|
public GridLayout(int rows, int cols) | Creates a grid layout with a given number of rows and columns. If cols or rows is zero, any numbers of components can be placed in a column or in a row. |
public GridLayout(int rows, int cols, int hgap, int vgap) | Creates a grid layout with a given number of rows and columns. Beside this, you can initialize the vertical and horizontal gap between each of rows and columns. |
Here is the screenshot of GridLayout demo application.
Code language: JavaScript (javascript)package gridlayoutdemo; import java.awt.*; import javax.swing.*; public class Main < public static void main(String[] args) < JFrame frame = new JFrame("GridLayout Demo"); JButton btn1 = new JButton("Button 1"); JButton btn2 = new JButton("Button 2"); JButton btn3 = new JButton("Button 3"); JButton btn4 = new JButton("Button 4"); JButton btn5 = new JButton("Button 5"); // create grid layout with 3 rows , 2 columns with horizontal // and vertical gap set to 10 JPanel panel = new JPanel(new GridLayout(3,2,10,10)); // add buttons to the panel panel.add(btn1); panel.add(btn2); panel.add(btn3); panel.add(btn4); panel.add(btn5); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,150); frame.getContentPane().add(panel); frame.setVisible(true); > >
How to Use GridLayout
Note: This lesson covers writing layout code by hand, which can be challenging. If you are not interested in learning all the details of layout management, you might prefer to use the GroupLayout layout manager combined with a builder tool to lay out your GUI. One such builder tool is the NetBeans IDE. Otherwise, if you want to code by hand and do not want to use GroupLayout , then GridBagLayout is recommended as the next most flexible and powerful layout manager.
If you are interested in using JavaFX to create your GUI, see Working With Layouts in JavaFX.
The following figure represents a snapshot of an application that uses the GridLayout class.
Click the Launch button to run GridLayoutDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
The complete code of this demo is in the GridLayoutDemo.java file.
A GridLayout object places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If the GridLayoutDemo window is resized, the GridLayout object changes the cell size so that the cells are as large as possible, given the space available to the container.
The code snippet below creates the GridLayout object and the components it manages.
GridLayout experimentLayout = new GridLayout(0,2); . compsToExperiment.setLayout(experimentLayout); compsToExperiment.add(new JButton("Button 1")); compsToExperiment.add(new JButton("Button 2")); compsToExperiment.add(new JButton("Button 3")); compsToExperiment.add(new JButton("Long-Named Button 4")); compsToExperiment.add(new JButton("5"));
The constructor of the GridLayout class creates an instance that has two columns and as many rows as necessary.
Use combo boxes to set up how much vertical or horizontal padding is put around the components. Then click the Apply gaps button. The following code snippet shows how your selection is processed by using the setVgap and setHgap methods of the GridLayout class:
applyButton.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e)< //Get the horizontal gap value String horGap = (String)horGapComboBox.getSelectedItem(); //Get the vertical gap value String verGap = (String)verGapComboBox.getSelectedItem(); //Set up the horizontal gap value experimentLayout.setHgap(Integer.parseInt(horGap)); //Set up the vertical gap value experimentLayout.setVgap(Integer.parseInt(verGap)); //Set up the layout of the buttons experimentLayout.layoutContainer(compsToExperiment); >>);
The GridLayout API
The following table lists constructors of the GridLayout class that specify the number of rows and columns.
Constructor | Purpose |
---|---|
GridLayout(int rows, int cols) | Creates a grid layout with the specified number of rows and columns. All components in the layout are given equal size. One, but not both, of rows and cols can be zero, which means that any number of objects can be placed in a row or in a column. |
GridLayout(int rows, int cols, int hgap, int vgap) | Creates a grid layout with the specified number of rows and columns. In addition, the horizontal and vertical gaps are set to the specified values. Horizontal gaps are places between each of columns. Vertical gaps are placed between each of the rows. |
The GridLayout class has two constructors:
Examples that Use GridLayout
The following table lists code examples that use the GridLayout class and provides links to related sections.
Example | Where Described | Notes |
---|---|---|
GridLayoutDemo | This page | Uses a 2-column grid. |
ComboBoxDemo2 | How to Use Combo Boxes | One of many examples that use a 1×1 grid to make a component as large as possible. |
LabelDemo | How to Use Labels | Uses a 3-row grid. |
How to Make a GUI Grid in Java
wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, 25 people, some anonymous, worked to edit and improve it over time.
This article has been viewed 233,507 times.
The Grid does nothing special at this stage, but with a little bit of research, you can add action listeners and a bit of logic to make a simple 2D game like tic-tac-toe, or more complicated ones like Battleship.
Note: This article uses Eclipse [1] X Research source for all of the examples so things may be different depending on your IDE. This should be very similar to what you’ll need in JCreator, but it’s rather useless for a GUI based IDE like NetBeans [2] X Research source though, mainly because of the drag and drop method of NetBeans.
- This name is more important than the previous one because it will have to be as single word or else it won’t be usable.
Import libraries. This brings all of the information you will need to write your code to this code. You’ll need to import javax.swing.JFrame, javax.swing.JButton, and java.awt.Gridlayout. These are put before the beginning of the class, somewhere on lines between 1 to 3, the order they’re on there doesn’t matter.
Create a constructor. The constructor makes a new instance of the buttongrid class allowing many different button grids to all have separate information. All constructors need to be named the same as their class. Constructors don’t need anything before it, but ‘public’ is often put there for ease of reference. Constructors are often placed as the first method in a class, so it goes right after the class name, it must, however be placed within the class. The buttongrid constructor needs parameters, which are put in brackets after the name of the constructor. The parameters in this example are integers ‘x’ and ‘y’.
- The frame must be named. To make sure it can be referenced outside of the ButtonGrid constructor method you place it out side of that method, but within the class. Most variables are named at the top of the class right before the constructor. To create a new frame you type: JFrame frame = new JFrame();
- Inside the constructor method we need to make sure that all of the buttons are put in the grid layout. To do this we set the layout of frame by typing: frame.setLayout(new GridLayout(x, y));
- Not necessarily mandatory, but to make the frame close when you hit the ‘x’ button in the top right hand corner we need to add the line: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- To make the frame a proper size so everything fits we need to run the pack command: frame.pack();
- Lastly for the frame we need to make it so it’s visible: frame.setVisible(true);
- The buttons that the user interacts with need to be made, but since we don’t know how many we need, they have to be named first. So right below the line where you create frame create the buttons: JButton[][] grid; The two sets of square brackets are there to say that the JButton’s in the grid are kept in a two-dimensional format, if there were only one set of square brackets then it would simply be a line of JButton’s, which still works, it’s just easier to reference which button is being created or interacted with when it’s two-dimensional.
- The JButton’s have been named, but we still have to say how many buttons there are. You need to add a line of code in the constructor that sets the amount: grid=new JButton[width][length];
- Now that it’s been determined that there will be a certain number of buttons, each must be created. The easiest way to do this is with two for loops, one for the x-axis, one for the y-axis. Inside the two loops we make a new button, and for ease of reference the example puts text inside each button so we know which button in the two-dimensional array is where. To create a button, inside the loop you need to put grid[x][y] = new JButton («(«+x+»,»+y+»)»);
Add buttons to frame. Inside the loop we need to put the buttons onto the frame with a simple command: frame.add(grid[x][y]);
Make ButtonGrid Instance. In your main class type: new ButtonGrid(3,3); The two threes make is a 3 by 3 grid, and any two positive numbers can be put in there.
Steps Code
public class ButtonGrid public static void main(String[] args) > >
import javax.swing.JFrame; import javax.swing.JButton; import java.awt.GridLayout; public class ButtonGrid .
public class ButtonGrid public ButtonGrid(int width, int length) > > .
public class ButtonGrid JFrame frame=new Jframe(); public ButtonGrid(int width, int length) frame.setLayout(new GridLayout(width,length)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); > > .
|JFrame frame=new JFrame(); //creates frame JButton[][] grid; //names the grid of buttons public ButtonGrid(int width, int length) //constructor with 2 parameters frame.setLayout(new GridLayout(width,length)); //set layout of frame grid=new JButton[width][length]; //allocate the size of grid for(int y=0; ylength; y++) for(int x=0; xwidth; x++) grid[x][y]=new JButton("("+x+","+y+")"); frame.add(grid[x][y]); //adds button to grid > > frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); > .
for(int y=0; ylength; y++) for(int x=0; xwidth; x++) grid[x][y]=new JButton("("+x+","+y+")"); frame.add(grid[x][y]); > > .
public static void main(String[] args) new ButtonGrid(3,3);//makes new ButtonGrid with 2 parameters > .
import javax.swing.JFrame; //imports JFrame library import javax.swing.JButton; //imports JButton library import java.awt.GridLayout; //imports GridLayout library public class ButtonGrid JFrame frame=new JFrame(); //creates frame JButton[][] grid; //names the grid of buttons public ButtonGrid(int width, int length) //constructor frame.setLayout(new GridLayout(width,length)); //set layout grid=new JButton[width][length]; //allocate the size of grid for(int y=0; ylength; y++) for(int x=0; xwidth; x++) grid[x][y]=new JButton("("+x+","+y+")"); //creates new button frame.add(grid[x][y]); //adds button to grid > > frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); //sets appropriate size for frame frame.setVisible(true); //makes frame visible > public static void main(String[] args) new ButtonGrid(3,3);//makes new ButtonGrid with 2 parameters > >
import javax.swing.JFrame; //imports JFrame library import javax.swing.JButton; //imports JButton library import java.awt.GridLayout; //imports GridLayout library
JFrame frame=new JFrame(); //creates frame JButton[][] grid; //names the grid of buttons