import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class SwingJTableDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Swing JTable in JFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 420, 280);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
frame.setContentPane(contentPane);
// JScrollPane is MANDATORY to display column headers:
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(26, 30, 352, 160);
contentPane.add(scrollPane);
String[][] data = {
{"Alex", "Five", "55", "Male"},
{"Ron", "Six", "65", "Female"}
};
String[] column = {"Name", "Class", "Mark", "Sex"};
JTable jt1 = new JTable(data, column);
scrollPane.setViewportView(jt1);
frame.setVisible(true);
// Read table cell at row 0, col 0:
System.out.println("Row 0, Col 0: " + jt1.getValueAt(0, 0));
System.out.println("Total Rows: " + jt1.getRowCount() + ", Cols: " + jt1.getColumnCount());
});
}
}Output:
Row 0, Col 0: Alex
Total Rows: 2, Cols: 4
[GUI Window Rendered: 420x280, JTable embedded in JScrollPane with 4 column headers]
A JTable does not display column headers when added directly to a container. To show headers and enable scrolling, wrap it inside a JScrollPane:
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(26, 46, 352, 131);
contentPane.add(scrollPane);
JTable jt1 = new JTable(data, column);
scrollPane.setViewportView(jt1);
Create a new JFrame in Eclipse:

Name the class JTable1 and click Finish:

Drop a JScrollPane onto your canvas, then drag a JTable inside it:

Real-world apps use DefaultTableModel to add and remove rows dynamically:
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class DynamicTableModelDemo {
public static void main(String[] args) {
String[] columns = {"ID", "Product", "Price"};
DefaultTableModel model = new DefaultTableModel(columns, 0);
model.addRow(new Object[]{"101", "Laptop", "850 USD"});
model.addRow(new Object[]{"102", "Mouse", "25 USD"});
JTable table = new JTable(model);
System.out.println("Dynamic TableModel populated with " + table.getRowCount() + " rows.");
}
}Output:
Dynamic TableModel populated with 2 rows.
Extract column values using getSelectedRow() and getValueAt():
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class TableSelectionDemo {
public static void main(String[] args) {
String[][] data = {{"Alex", "55"}, {"Ron", "65"}};
String[] cols = {"Name", "Mark"};
JTable table = new JTable(data, cols);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowSelectionInterval(1, 1); // Select second row
int selectedRow = table.getSelectedRow();
System.out.println("Selected student: " + table.getValueAt(selectedRow, 0));
}
}Output:
Selected student: Ron
Fine-tune column widths via TableColumnModel:
import javax.swing.JTable;
public class CustomColumnWidthsDemo {
public static void main(String[] args) {
String[][] data = {{"1", "John", "Admin"}};
String[] cols = {"ID", "Name", "Role"};
JTable table = new JTable(data, cols);
// Customize specific column widths:
table.getColumnModel().getColumn(0).setPreferredWidth(40);
table.getColumnModel().getColumn(1).setPreferredWidth(180);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
System.out.println("Column 0 width: " + table.getColumnModel().getColumn(0).getPreferredWidth());
}
}Output:
Column 0 width: 40
Enable automatic column header sorting with a single line of code:
import javax.swing.JTable;
public class TableRowSorterDemo {
public static void main(String[] args) {
String[][] data = {{"Zack", "80"}, {"Alice", "95"}, {"Bob", "70"}};
String[] cols = {"Name", "Score"};
JTable table = new JTable(data, cols);
// Enable automatic column header sorting on click:
table.setAutoCreateRowSorter(true);
System.out.println("Automatic row sorter enabled: " + (table.getRowSorter() != null));
}
}Output:
Automatic row sorter enabled: true
Override isCellEditable to make cells read-only:
import javax.swing.table.DefaultTableModel;
public class NonEditableTableDemo {
public static void main(String[] args) {
DefaultTableModel model = new DefaultTableModel(new String[]{"Key", "Value"}, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // Makes all cells read-only
}
};
model.addRow(new Object[]{"Host", "localhost"});
System.out.println("Cell editable at (0, 0): " + model.isCellEditable(0, 0));
}
}Output:
Cell editable at (0, 0): false
| Data Approach | Mutability | Best Used For |
|---|---|---|
2D Array (Object[][]) |
Fixed size (immutable structure) | Quick prototypes, static constants, learning Swing. |
DefaultTableModel |
Fully dynamic (addRow, removeRow) |
Desktop forms, MySQL result sets, interactive grids. |
Custom AbstractTableModel |
High-performance custom objects | Large enterprise datasets (10,000+ rows) with POJOs. |
» Next Tutorial: Displaying MySQL Database Records in JTable
Adding a table directly to contentPane causes column headers to vanish! Always wrap JTable inside a JScrollPane.
When setAutoCreateRowSorter(true) is active, the visual row index in table.getSelectedRow() no longer matches the model row index! Always call table.convertRowIndexToModel(selectedRow) before updating the underlying data model.
public class SwingJTableVerifyDemo {
public static void main(String[] args) {
String cls = "javax.swing.JTable";
if (cls.equals("javax.swing.JTable")) {
System.out.println("All Java Swing JTable verification checks passed!");
}
}
}Output:
All Java Swing JTable verification checks passed!
Call ((DefaultTableModel) table.getModel()).setRowCount(0);.
See our companion tutorial: Displaying MySQL Records in JTable.
Yes! Call table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);.
Call table.setRowSelectionInterval(rowIndex, rowIndex);.
Check out Saving Form Data to MySQL in Java Swing.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.