Home » Desktop Java » swing » JAVA Swing Table Example

About Jyoti Jha

Jyoti Jha
Jyoti is a tech enthusiast and is an avid programmer. She holds a post graduation degree in (M.Tech) Computer Science Engineering from Thapar Univeristy, Patiala, India. Post her graduate studies, she has worked in Software companies such as SLK Software and Aricent, India as Software Engineer in various projects primarily in the field of Requirement analysis and design, implementing new algorithms in C++ and JAVA used in ISDN network and designing databases and. She is inquisitive about socio economic reforms as well as advancement in technical fronts and keep herself informed with TED talks and various blogs.

JAVA Swing Table Example

1. Introduction

In this example we will learn how to create a Table using JTable component in Swing. Data can be viewed or edited using the JTable component. JScrollPane is widely used to display the data. Model Implementation can be achieved using either AbstractDataModel or DefaultDataModel class. AbstractDataModel by default provides the implementation of most of the methods of TableModel interface. We will look into the meaning of various other terms as we proceed.

2. JAVA Swing Table Example

This Example demonstrates how to create a table using Swing in eclipse.

Prerequisite

This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work. To learn how to install WindowBuilder tool please visit the Setup section 2.1 of the following link click here.

2.1 JAVA Swing Table

Create a new JAVA project lets say swing_1

  • Go to src→ right click→ New→ Other→ WindowBuilder→ select Swing Designer→ Application Window
JAVA Swing Table

JAVA Swing Table

JAVA Swing Table

JAVA Swing Table

Enter the name of the application(eg. SwingTableExample ) and click finish.

This will create SwingTableExample.java file and will provide Source and Design tab.

3. Code

The Table exhibits the following property

  • The entire row is highlighted if an individual cell is clicked.
  • Vertical or horizontal scroll bar appears on decreasing the window size.
  • A column can be dragged and moved to anywhere in the frame.
  • A cell can be edited by double clicking on it

In this example we will create a table using JTable which contains a student’s academic record containing 6 column and 5 rows. We will thoroughly visit the code and learn how to create a table.

SwingTableExample.java

package swing_1;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import java.awt.GridLayout;

  private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("TableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        SwingTableExample newContentPane = new SwingTableExample();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

The above code creates a Frame which holds the ContentPane and all other components. Here we are creating an object i.e, newContentPane of class SwingTableExample. The SwingTableExample class is described below.

SwingTableExample.java

  
public class SwingTableExample extends JPanel {
    private boolean DEBUG = false;

    public SwingTableExample() {
        super(new GridLayout(1,0));

        JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);
    }

SwingTableExample extends the JPanel class and adds GridLayout to its window Pane. A table is created in the constructor of SwingTableExample class using JTable class which again creates a custom TableModel using AbstractTableModel when instantiated i.e, new MyTableModel() in this case.

Table can be created by using different JTable constructors. Below are the type of constructors.

JTable() Constructs a default JTable that is initialized with a default data model, a default column model, and a default selection model.

JTable(int numRows, int numColumns) Constructs a JTable with numRows and numColumns of empty cells using DefaultTableModel.

JTable(Object[][] rowData, Object[] columnNames) Constructs a JTable to display the values in the two dimensional array, rowData, with column names, columnNames.

JTable(TableModel dm) Constructs a JTable that is initialized with dm as the data model, a default column model, and a default selection model.

JTable(TableModel dm, TableColumnModel cm) Constructs a JTable that is initialized with dm as the data model, cm as the column model, and a default selection model.

JTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) Constructs a JTable that is initialized with dm as the data model, cm as the column model, and sm as the selection model.

JTable(Vector rowData, Vector columnNames) Constructs a JTable to display the values in the Vector of Vectors, rowData, with column names, columnNames.

setPreferredScrollableViewportSize(Dimension size) sets the preferred size of the viewport for this table.

void setFillsViewportHeight(boolean fillsViewportHeight) sets whether or not this table is always made large enough to fill the height of an enclosing viewport. If the preferred height of the table is smaller than the viewport, then the table will be stretched to fill the viewport. In other words, this ensures the table is never smaller than the viewport. The default for this property is false.

ScrollPane is created and the table is added to it. Finally, ScrollPane is added to the Panel.

Class MyTableModel describes the content of the data and implements the methods such as, getRowCount() , getColumnCount(), getValueAt(int row, int column) etc.

SwingTableExample.java

 class MyTableModel extends AbstractTableModel {

        String[] columnNames = {"Name",
                                "Degree",
                                "Board/University",
                                "Year of Passing",
                                "CGPA",
                                "Part-Time"};

        Object[][] data = {
        {"Saira", "B.Tech",
         "VTU", new Integer(2015), new Float(8.33), new Boolean(false)},
        {"Smaira", "B.Sc",
             "CBSE", new Integer(2007), new Float(7.77), new Boolean(true)},
        {"John", "M.tech",
                 "IIT", new Integer(2009), new Float(8.77), new Boolean(false)},
        {"Jia", "M.Sc",
                     "Thapar", new Integer(2011), new Float(7.21), new Boolean(true)},
        {"Kerry", "B.Com",
                         "DU", new Integer(2014), new Float(8.92), new Boolean(false)}
        
        };

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

          public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col < 1) {
                return false;
            } else {
                return true;
            }
        }

         public void setValueAt(Object value, int row, int col) {
     
           data[row][col] = value;
            fireTableCellUpdated(row, col);
        }

      
    }

Here columnNames is the header or name of the column. Object data store the content of the array in two dimensional array. In this Example every cell is editable except the Name column cell as we have fixed the Name column.
getColumnClass() returns the class of each cell and is required to be implemented if we need to see checkboxex in the last column. This method is used by JTable.

getColumnCount() returns the count of the columns present in the table. getRowCount() returns the number of rows present in the table.isCellEditable returns a Boolean value i.e true or false if a cell is editable or not respectively. setValueAt(int row, int col) sets the value of cell present at the mentioned row and column. This method is implemented when you want to change the value of the cell of a table.

After execution of the code Table will look like this:

JAVA Swing Table Example

JAVA Swing Table

The table can be edited by double clicking on the cell and replacing the old value with the new one. For instance here we have the value of 2 row and 2 column, i.e, degree of smaira from B.Sc to B.Com. Image is shown below.

Altering the cell value

Altering the cell value

4. Download

This was an example of creation of JAVA Swing Table.

Download
You can download the full source code of this example here: SwingTableExample
(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