JTable: Displaying Tabular Data
JTable is used to show data in rows and columns, similar to a small Excel table. It is useful for displaying structured records.
Example: Student data in a JTable
This example defines a 2D array for table data and a 1D array for column names, then passes both to JTable.
import javax.swing.*;
import java.awt.*;
class MyFrame extends JFrame {
MyFrame() {
setTitle("Components - Table");
String ColumnName[] = { "Name", "Year", "Course" };
String Data[][] = { { "Utsab", "2024", "BEIT" },
{ "Ram", "2025", "BECE" },
{ "Hari", "2023", "BESE" } };
JTable t1 = new JTable(Data, ColumnName);
add(t1);
setLayout(new FlowLayout());
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class JTabledemo {
public static void main(String arr[]) {
new MyFrame();
}
}What is JTable?
A JTable displays data in tabular form. Each row represents one record, and each column represents a field (e.g., Name, Year, Course).
- Suitable for displaying structured, record-based information.
- Data is often provided as arrays or via table models.
- Can be placed inside a
JScrollPaneto add scrollbars.
Line-by-line: Understanding the JTable example
We focus on how the column names and data array are defined and passed to the table.
String ColumnName[] = { "Name", "Year", "Course" };
Defines the header names for each column of the table.
String Data[][] = {{ "Utsab", "2024", "BEIT" }, { "Ram","2025", "BECE" }, { "Hari", "2023", "BESE" } };
Creates a 2D array where each inner array is one row (student record) and each element corresponds to a column.
JTable t1 = new JTable(Data, ColumnName);
add(t1);
Creates the JTable using the data and column names, then adds it to the frame so it becomes visible.
Where JTable is used
Tables are everywhere in real applications: student records, invoices, reports, and more. JTable provides a flexible way to show and edit such data.