Home » Desktop Java » swing » Java Swing GridLayout Example

About Koushik Sanyal

Koushik Sanyal
Koushik Sanyal is a resident of a small town Uttarpara, in the suburbs of Kolkata (erstwhile Calcutta) which is one of the biggest cities in India and capital of the state of ‘West Bengal’. He completed Diploma in Information Technology from DoEACC Society (Currently NIELIT), a government of India run autonomous society dedicated for pertaining training in Information Technology. He has spent more than 11 years in IT professional domain as Trainer, Software Developer and Senior Software Developer. Currently he's working as a ‘Senior Software Developer’ in java domain at ‘Greenfield Software Pvt. Ltd in Kolkata, India.

Java Swing GridLayout Example

In Swing, in order to arrange components in a form, dialog box etc. in user friendly manner layout manager is found to be very useful. There are several layout managers. GridLayout is such layout manager.

1. Introduction

GridLayout actually forms a grid like arrangement of cells. This is just like one excel spreadsheet where each cell is of same size. If the parent window is resized, the grids are also resized, keeping the same aspect ratio. Components are required to be added in each cell.

2. Technologies Used

  • Java  (jdk 1.6.x or higher will be fine)
  • Eclipse ( Galileo or higher version is required)

3. Overview

Like other layout manager classes, java.awt.GridLayout class implements java.awt.LayoutManager.

At the time GridLayout object is created, number of rows and number of columns must be mentioned. For example GridLayout layout = new GridLayout(2,3). Here 2 refers to number of rows and 3 refers to number of columns. The grid mentioned above will have 6 cells in it, 3 in each row.

While adding components in cells, if the cell no is not specified, the components will be added to the cells starting from upper leftmost cell to lower rightmost cell, in this direction i.e. addition will start from the leftmost cell of the topmost row moving rightwards, and then comes down to the next row (if available) and gets filled up in the same way.

If component is required to be added in a specific cell, then row number and column number is required to be specified while adding the component. For example 0,0 cell number refers to the leftmost cell of the first i.e. topmost row.

4. Description of GridLayout feature in the example

In the example a GridLayout of 2 rows and 3 columns are created. In all except 5th cell, JEditPane is attached. In the 5th cell, one JSplitPane component is added. In the right side of the JSplitPane component, one JList component is added which shows cell numbers. In the right side of the JSplitPane, one JFileChooser is added to show only .txt files in system drive.

JTextPane and JSplitPane components added to a 2X3 grid layout.

Once a text file is chosen, keeping 1st Box option selected from the JList, after clicking the Open button of the JFileChooser component, content of the text file appears in cell 1.

Content of .txt file appears in cell-1 of the grid.

Once a text file is chosen, keeping 6th Box option selected from the JList, after clicking the Open button of the JFileChooser component, content of the text file appears in cell 6.

Content of the .txt file appears in cell-6 of the grid.

If a file is opened, without selecting any option in JList, error message is generated.

Error message shows that no option is selected from the list.

5. Description of GridLayout feature in the source code

Here first of all one JPanel object is created for GridLayout of dimension 2X3 and then components are added to the grid in turn. To the JFileChooser object, ActionListner is assigned which is taking care of the click to Open button of the JFileChooser component. As per the choice of the JList component, the content of the file is shown in the corresponding cell of the grid.

SwingGridLayoutExampleFrame.java

package com.javacodegeeks.example.swing.layoutmanager.gridlayout;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

public class SwingGridLayoutExampleFrame extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 8008949174170019398L;
	
	public SwingGridLayoutExampleFrame(){
		JPanel panel = new JPanel(new GridLayout(2,3));
		final JEditorPane textField1 = new JEditorPane();
		JScrollPane scrollPane1 = new JScrollPane(textField1);
		panel.add(scrollPane1,0,0);
		
		final JEditorPane textField2 = new JEditorPane();
		JScrollPane scrollPane2 = new JScrollPane(textField2);
		panel.add(scrollPane2,0,1);
		
		final JEditorPane textField3 = new JEditorPane();
		JScrollPane scrollPane3 = new JScrollPane(textField3);
		panel.add(scrollPane3);
		
		final JEditorPane textField4 = new JEditorPane();
		JScrollPane scrollPane4 = new JScrollPane(textField4);
		panel.add(scrollPane4);
		
		final JEditorPane textField5 = new JEditorPane();
		
		JSplitPane splitPane = new JSplitPane();
		splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
		splitPane.setDividerLocation(50);
		final JList list = new JList(new String[]{"1st Box","2nd Box","3rd Box","4th Box","6th Box"});
		splitPane.setLeftComponent(list);
		final JFileChooser fileChooser = new JFileChooser();
		fileChooser.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent evt) {
				if (evt.getActionCommand().equals(javax.swing.JFileChooser.APPROVE_SELECTION)) {
					String selected = list.getSelectedValue() != null ? list.getSelectedValue().toString() : null;
					if(selected == null)
						JOptionPane.showMessageDialog(fileChooser, "You must choose one item from the list to proceed.");
					else{
						File file = fileChooser.getSelectedFile();
						if(file.getName().endsWith(".txt")){
							char[] content = readFile(file);
							if(content == null){
								JOptionPane.showMessageDialog(fileChooser, "File size too large.");
							}else if(content.length == 0){
								JOptionPane.showMessageDialog(fileChooser, "Empty file.");
							}else{
								switch(selected.charAt(0)){
								case '1':	textField1.setText(new String(content));
								break;
								case '2':	textField2.setText(new String(content));
								break;
								case '3':	textField3.setText(new String(content));
								break;
								case '4':	textField4.setText(new String(content));
								break;
								case '6':	textField5.setText(new String(content));
								break;
								}
							}
						}
					}
			    } 
			}
		});
		FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
		fileChooser.setFileFilter(filter);
		splitPane.setRightComponent(fileChooser);
		panel.add(splitPane);
		
		JScrollPane scrollPane5 = new JScrollPane(textField5);
		panel.add(scrollPane5);
		
		add(panel);
		pack();
	}
	
	private char[] readFile(File inputFile){
		BufferedReader inputReader = null;
		char[] content = null;
		long availableHeap = Runtime.getRuntime().freeMemory();
		long fileSize = inputFile.length();
		try {
			if(fileSize <= availableHeap){
				content = new char[(int)inputFile.length()];
				inputReader = new BufferedReader(new FileReader(inputFile)); 

				inputReader.read(content);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return content;
	}

}

line 32: One JPanel object is created for GridLayout of size 2X3.
line 35: JScrollPane component object created for JEditorPane component object, is added to (0,0)th i.e. the leftmost cell of the first row of the grid.
line 39: Next JScrollPane component object created for JEditorPane component object, is added to (0,1)th i.e. the 2nd cell from the left, of the first row of the grid.
line 43: Next JScrollPane component object created for JEditorPane component object, is added to the grid. Since no cell is specified, the component is added to the next available i.e. 3rd cell of the first row. This is as per the default order of addition described above.
line 47: Next JScrollPane component object created for JEditorPane component object, is added to the grid. Since no cell is specified, the component is added to the next available i.e. 1st cell of the 2nd row. This is as per the default order of addition described above.
line 94: One JSplitPane component object is added to the grid.
line 97: Next JScrollPane component object created for JEditorPane component object, is added to the grid. Since no cell is specified, the component is added to the next available as per the default order of addition described above.

6. Summary

This example shows a scenario to use GridLayout while developing UI. There can numerous such scenarios for use of this. For any further reading, supplied links can be referred.

7. Download the Source Code

This was an example of Java GridLayout.

Download
You can download the full source code of this example here: Swing GridLayout Example
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of