Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Creating a JTable using Swing in Java

In this lesson, you will learn.

  • Working with JTable
  • Constructors and Methods of JTable
  • Examples
  • Creating a Custom Class and Storing Data in a Table
  • Examples

 

What is a JTable?

  1. A Swing component displays data in a tabular format (rows and columns).
  2. It is highly customizable and can display, edit, and interact with data.

 

 

Constructors of JTable

Constructor Description
JTable() Creates a default table with no data.
JTable(int rows, int columns) Creates a table with a specified number of rows and columns.
JTable(Object[][] rowData, Object[] columnNames) Creates a table with the given data for rows and column names.
JTable(TableModel model) Creates a table that uses the specified data model.
JTable(TableModel model, TableColumnModel cm) Creates a table that uses the specified data model and column model.
JTable(TableModel model, TableColumnModel cm, ListSelectionModel sm) Creates a table that uses the specified data model, column model, and selection model.
JTable(Vector rowData, Vector columnNames) Creates a table with the given data as vectors for rows and column names.

 

Creating a JTable

1. JTable()

This is the default constructor and creates an empty JTable with a default TableModel (an instance of DefaultTableModel) that has zero columns and zero rows.

You need to explicitly set the data and column headers later.

Example 1: Creating JTable

package jtables;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class JTableExample1 {
    public static void main(String[] args) {
            JFrame frame = new JFrame("Empty JTable Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JTable table = new JTable(); // Creates an empty JTable

            // Create a DefaultTableModel and set data
            DefaultTableModel model = new DefaultTableModel();
            model.addColumn("Name");
            model.addColumn("Age");
            model.addRow(new Object[]{"Alice", 30});
            model.addRow(new Object[]{"Bob", 25});
            table.setModel(model); // Set the model for the JTable

            JScrollPane scrollPane = new JScrollPane(table);
            
            frame.getContentPane().add(scrollPane);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }
}


 

2. JTable(Object[][] rowData, Object[] columnNames)

This constructor creates an JTable initialized object with the provided 2D array of data (rowData) and an array of column names (columnNames).

Internally, it creates a DefaultTableModel using this data. This is a convenient way to quickly display static data.

Example 2: Creating a JTable

package jtables;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

public class JTableExample2 {
	public static void main(String[] args) {
		Object[][] data = {
				{"John", "Doe", 30},
				{"Jane", "Smith", 25},
				{"Peter", "Jones", 40}
		};
		String[] columnNames = {"First Name", "Last Name", "Age"};

		JTable table = new JTable(data, columnNames); // Initialize with data and column names

		JScrollPane scrollPane = new JScrollPane(table);
		JFrame frame = new JFrame("Data and Column Names JTable Example");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().add(scrollPane);
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
	}
}


 

3. JTable(TableModel dm)

This constructor creates a JTable that displays the data and column headers provided by the specified TableModel object (dm).

This is the most flexible approach, as you can use any custom implementation of the TableModel interface, allowing for more complex data sources and behaviors.

Example 3: Creating a JTable

package jtable;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class JTableExample {
	public static void main(String[] args) {
		// Frame setup
		JFrame frame = new JFrame("JTable Example");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(500, 300);

		// Column names
		String[] columnNames = {"ID", "Name", "Salary"};

		// Data for the table
		Object[][] data = {
				{1, "John Doe", 50000},
				{2, "Jane Smith", 60000},
				{3, "Kathy Green", 70000}	
		};

		// Table model
		DefaultTableModel model = new DefaultTableModel(data, columnNames);

		// JTable setup
		JTable table = new JTable(model);
		table.setAutoCreateRowSorter(true); // Enable sorting

		// Scroll pane setup
		JScrollPane scrollPane = new JScrollPane(table);
		frame.add(scrollPane);

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

 

Output

 

Summary of Common Methods in JTable

Method Description
void setModel(TableModel dataModel) Sets the data model for the table.
TableModel getModel() Returns the table’s data model.
void setColumnModel(TableColumnModel columnModel) Sets the column model for the table.
TableColumnModel getColumnModel() Returns the table’s column model.
void setSelectionModel(ListSelectionModel newModel) Sets the selection model for the table.
ListSelectionModel getSelectionModel() Returns the table’s selection model.
int getRowCount() Returns the number of rows in the table.
int getColumnCount() Returns the number of columns in the table.
Object getValueAt(int row, int column) Returns the value for the cell at the specified row and column.
void setValueAt(Object aValue, int row, int column) Sets the value for the cell at the specified row and column.
boolean isCellEditable(int row, int column) Returns true if the cell at the specified row and column is editable.
void setAutoCreateRowSorter(boolean autoCreateRowSorter) Sets whether the table should create a row sorter automatically.
void setRowHeight(int rowHeight) Sets the height, in pixels, of all rows in the table.
void setColumnSelectionAllowed(boolean columnSelectionAllowed) Sets whether column selection is allowed.
void setRowSelectionAllowed(boolean rowSelectionAllowed) Sets whether row selection is allowed.
void setShowGrid(boolean showGrid) Sets whether the table should draw a grid.
void setGridColor(Color gridColor) Sets the color of the grid.
void addRowSelectionInterval(int index0, int index1) Adds a selection interval to the table.
void removeRowSelectionInterval(int index0, int index1) Removes a selection interval from the table.

 

 

Creating a Custom Class and Storing Data in a Table

Now, let’s say you have a custom class and you want to display a list of objects of that class in a JTable. You’ll typically create a custom data model (by extending AbstractTableModel) or use DefaultTableModel and populate it with data extracted from your custom objects.

Example- Storing Custom Object in JTable

package jtables;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import java.util.ArrayList;
import java.util.List;

// Custom Person class
class Person {
	private String firstName;
	private String lastName;
	private int age;

	public Person(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public int getAge() {
		return age;
	}
}

public class CustomObjectTableExample {

	public static void main(String[] args) {
		// Create a list of Person objects
		List personList = new ArrayList<>();
		personList.add(new Person("Amit", "Kumar", 28));
		personList.add(new Person("Himani", "Chaudhary", 35));
		personList.add(new Person("Charlie", "Chaplin", 50));

		// Column names
		String[] columnNames = {"First Name", "Last Name", "Age"};

		// Create a DefaultTableModel
		DefaultTableModel model = new DefaultTableModel(columnNames, 0); 
		// 0 indicates initial row count

		// Populate the model with data from the Person objects
		for (Person person : personList) {
			Object[] rowData = {person.getFirstName(), person.getLastName(), person.getAge()};
			model.addRow(rowData);
		}

		// Create the JTable with the DefaultTableModel
		JTable table = new JTable(model);

		// Put the table in a scroll pane
		JScrollPane scrollPane = new JScrollPane(table);

		// Create and set up the main frame
		JFrame frame = new JFrame("Custom Object JTable Example");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().add(scrollPane);
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
	}
}


 

 

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review