Swing Tables: JTable, Table Models, Sorting and Filtering
Displaying tabular data with JTable: simple tables, custom AbstractTableModel classes and their events, column classes, the column model, resizing, selection, view versus model indexes, and sorting and filtering rows with TableRowSorter and RowFilter.
kvi5hnuCode Sprout team member13 min readOn this page
Part 12 covers the two most powerful Swing components, tables and trees, and then turns to advanced 2D graphics, images and printing. Tables come first. JTable displays a two-dimensional grid of objects with column headers, lets the user resize and reorder columns, select rows or cells, sort by clicking a header, and edit cells. A basic table takes a few lines of code; behind it is a set of cooperating models that you can customize piece by piece. This article covers the data model, rows and columns, sorting and filtering. The next one covers how cells are drawn and edited.
A simple table
The quickest table wraps a two-dimensional array:
String[] columnNames = {"Name", "Symbol", "Number", "Mass", "Gas"};
Object[][] cells = {
{"Hydrogen", "H", 1, 1.008, true},
{"Carbon", "C", 6, 12.011, false},
...
};
var table = new JTable(cells, columnNames);
table.setAutoCreateRowSorter(true);
frame.add(new JScrollPane(table));
Autoboxing turns the numbers and booleans into Integer, Double and Boolean objects. Put the table into a scroll pane: the scroll pane shows the column header and keeps it in view while the rows scroll. (Without a scroll pane, you must add table.getTableHeader() yourself, for example to BorderLayout.NORTH.)
This table already has a lot of behavior. The user can drag a column header to move the column (only the view changes, not the data), drag a header border to resize a column, click to select rows, and, thanks to setAutoCreateRowSorter(true), click a header to sort by that column and again to reverse the order. Double-clicking a cell starts editing it, but the edits go into the array without any checks, which is rarely what you want. table.print() opens a print dialog and prints the table across pages, and setFillsViewportHeight(true) makes the table fill the whole scroll pane even when it has few rows, which matters for drag and drop and for the background color.
Table models
The array constructor is fine for a demo. In real programs, implement a table model: an object that tells the table how many rows and columns there are and what is in each cell. The table asks the model only for the cells it currently displays, so the data can stay where it is (in a list of records, a database result, or a formula) without copying it into an array.

AbstractTableModel implements most of the TableModel interface; you supply three methods:
public int getRowCount()
public int getColumnCount()
public Object getValueAt(int row, int column)
Usually you also override getColumnName (otherwise the columns are named A, B, C, like a spreadsheet) and getColumnClass (see below). A computed model needs no storage at all; the demo's temperature table calculates each cell in getValueAt. For data in a list, write a model that wraps the list:
class ElementModel extends AbstractTableModel {
private final List<Element> rows;
public int getRowCount() { return rows.size(); }
public int getColumnCount() { return 5; }
public Object getValueAt(int r, int c) {
Element e = rows.get(r);
return switch (c) { case 0 -> e.name(); case 1 -> e.symbol(); ... };
}
}
For a model backed by a database query, getValueAt can position a scrollable result set or cached row set (Articles 62 and 63) on the requested row; for large results, fetch and cache pages of rows.
Telling the table about changes
The table caches nothing about the data, but it must know when to repaint and when the number of rows changes. When the data changes, the model must fire an event. AbstractTableModel provides the methods:
| Method | Use after |
|---|---|
fireTableCellUpdated(row, column) | one cell changed |
fireTableRowsUpdated(first, last) | values in some rows changed |
fireTableRowsInserted(first, last) | rows were added |
fireTableRowsDeleted(first, last) | rows were removed |
fireTableDataChanged() | anything changed, same columns |
fireTableStructureChanged() | the columns changed |
Firing the most specific event keeps the selection and scroll position stable; fireTableDataChanged clears the selection. As always in Swing, change the model on the event dispatch thread, because the table reads it there.
DefaultTableModel
DefaultTableModel stores its data in vectors of vectors and offers addRow, insertRow, removeRow, setValueAt and addColumn, firing the right events itself. It is convenient for small, simple tables, but its data are untyped Objects and copying your data into it duplicates them. Note one difference: AbstractTableModel.isCellEditable returns false, while DefaultTableModel makes every cell editable.
Editing through the model
For a cell to be editable, the model's isCellEditable(row, column) must return true. When the user finishes editing, the table calls the model's setValueAt(value, row, column), which should store the value (validating it if needed) and fire fireTableCellUpdated. The demo makes only the name column editable and logs the events. The next article shows how to choose the editor component for a cell.
Working with rows and columns
Tables are asymmetric: they are built for many rows of the same structure, like a database result, and rows and columns are handled in different ways.
Column classes
Override getColumnClass to tell the table what kind of values a column holds. The table uses it to choose a renderer and the sorter uses it to choose a comparison:
| Column class | Displayed as |
|---|---|
Boolean | check box |
Icon, ImageIcon | image |
Number, Integer, ... | right-aligned text |
Double, Float | number formatted for the locale |
Date | date formatted for the locale |
Object (the default) | the toString string |
The default getColumnClass returns Object.class, so without overriding it, booleans appear as the words "true" and "false" and numbers sort as strings ("10" before "9").
The column model
The table keeps the columns in a TableColumnModel, a list of TableColumn objects in view order. A TableColumn knows which model column it displays (getModelIndex), its widths, its header value, and its renderer and editor. Get one with:
TableColumn column = table.getColumnModel().getColumn(viewIndex);
To hide a column, remove it from the view with table.removeColumn(column); the model still has the data. Keep the TableColumn object to bring it back with table.addColumn(column), which appends it at the end; moveColumn(from, to) moves it elsewhere. You can even add new TableColumn(modelIndex) to show a model column twice. The demo moves, hides and re-adds columns and prints the result.
Column widths and resizing
TableColumn has setPreferredWidth, setMinWidth, setMaxWidth and setResizable; the default preferred width is 75 pixels. When the user drags a column border, the table by default keeps its total width and takes the space from the columns to the right. setAutoResizeMode chooses another policy:
| Mode | Effect |
|---|---|
AUTO_RESIZE_SUBSEQUENT_COLUMNS | adjust all columns to the right (default) |
AUTO_RESIZE_NEXT_COLUMN | adjust only the next column |
AUTO_RESIZE_LAST_COLUMN | adjust only the last column |
AUTO_RESIZE_ALL_COLUMNS | adjust all columns |
AUTO_RESIZE_OFF | never adjust others; the table gets wider (with a horizontal scroll bar) |
AUTO_RESIZE_OFF is the right mode for tables with many columns. The demo lays out the same columns with AUTO_RESIZE_OFF (columns at their preferred widths, table 490 pixels wide) and with AUTO_RESIZE_ALL_COLUMNS at 400 pixels (all columns shrunk proportionally, respecting the 40-pixel maximum of the first column).
Row heights
Row heights belong to the table itself: setRowHeight(height) for all rows, setRowHeight(row, height) for one row. The cell content gets the height minus the row margin (setRowMargin, 1 pixel by default). Set larger heights for tables with images or multi-line cells; with large system fonts, compute the height from the font metrics rather than hard-coding it.
Selection
By default, clicking selects a whole row, and the user can select several rows with Ctrl and Shift. Choose the mode with table.getSelectionModel().setSelectionMode(...) and one of SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION and MULTIPLE_INTERVAL_SELECTION. Turn on column selection with setColumnSelectionAllowed(true); rows and columns together give cell selection, which setCellSelectionEnabled(true) sets in one call.
getSelectedRows() and getSelectedColumns() return the selection, and getSelectedRow() the first selected row (or -1). To react to selection changes, add a ListSelectionListener to the selection model and ignore events with getValueIsAdjusting() set, which arrive while the user drags the mouse.
View indexes and model indexes
Here is the most common source of table bugs. Every index the JTable hands you (selected rows, the row under the mouse, getValueAt on the table) is a view index. Once the user sorts, filters or moves columns, view indexes differ from model indexes. Convert before accessing the model:
int modelRow = table.convertRowIndexToModel(table.getSelectedRow());
Element selected = model.get(modelRow);
int modelColumn = table.convertColumnIndexToModel(viewColumn);
convertRowIndexToView and convertColumnIndexToView go the other way. In the demo, after sorting, the selected view rows [1, 2, 4] were model rows [1, 6, 4]. Note that JTable.getValueAt(row, column) takes view indexes and converts them itself, while TableModel.getValueAt takes model indexes.
Sorting rows
setAutoCreateRowSorter(true) installs a default sorter. For control, install a TableRowSorter yourself:
var sorter = new TableRowSorter<ElementModel>(model);
table.setRowSorter(sorter);
sorter.setSortable(4, false); // no sorting by this column
sorter.setComparator(1, Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder())); // custom order for column 1
sorter.setSortKeys(List.of(new RowSorter.SortKey(3, SortOrder.DESCENDING))); // sort from code
Sorting changes only the view; the model's rows stay in place. The sort keys list allows secondary keys: the demo sorts by the Gas column and, within equal values, by symbol. If you set no comparator for a column, the sorter decides as follows:
- If the column class is
String, compare with the locale'sCollator(Article 73), which handles accents and case sensibly. - Otherwise, if the column class implements
Comparable, usecompareTo. - Otherwise, if a
TableStringConverteris set (setStringConverter), compare the strings it produces with the collator. - Otherwise compare the
toStringresults with the collator.
This is why getColumnClass matters for sorting too. By default, the sorter does not re-sort when the model changes; call setSortsOnUpdates(true) if updated rows should move to their new sorted position right away.
Filtering rows
A TableRowSorter also filters: rows rejected by its RowFilter are hidden from the view. The RowFilter class provides ready-made filters:
RowFilter.numberFilter(RowFilter.ComparisonType.AFTER, 9, 2) // column 2 > 9
RowFilter.regexFilter("(?i)^[a-h]", 0) // column 0 matches the regex
RowFilter.dateFilter(RowFilter.ComparisonType.BEFORE, date, 4)
RowFilter.andFilter(List.of(f1, f2)), orFilter(...), notFilter(f)
The comparison types are EQUAL, NOT_EQUAL, AFTER and BEFORE. Without column indexes, a filter looks at all columns and accepts the row if any column matches. Two caveats: if the cell's class differs from the class of the number you pass, the number filter compares longValue()s, so fractions are truncated (with an Integer 100, a Double cell 100.7 is not after 100); pass a number of the column's class, such as 100.0 for a Double column, and regexFilter uses find, not matches, so anchor the expression with ^ and $ if needed. When the search text comes from the user, quote it with Pattern.quote, or a typed "(" will throw a PatternSyntaxException.
For other criteria, subclass RowFilter<M, I>, where M is the model type and I the row identifier type (Integer for tables), and implement include:
var evenNumbers = new RowFilter<ElementModel, Integer>() {
public boolean include(Entry<? extends ElementModel, ? extends Integer> entry) {
return (Integer) entry.getValue(2) % 2 == 0;
}
};
sorter.setRowFilter(evenNumbers);
The Entry provides the model, the row identifier (the model row index) and the row's values. A filter is applied when you set it. If its criteria change later (say, a set of hidden rows grows), call setRowFilter again, or sorter.sort(), to reapply it. setRowFilter(null) shows all rows. Filtering changes table.getRowCount(), but not the model's row count, as the demo shows.
An element browser
This program combines the techniques: a record-based model, a sorter with a search field (quoted, case-insensitive regex over the name and symbol columns) and a "gases only" filter combined with andFilter, a status line updated from sorter and selection events using convertRowIndexToModel, a header pop-up menu for hiding and showing columns, and printing.
import java.awt.*;
import java.awt.print.PrinterException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.*;
public final class ElementTableFrame extends JFrame {
private static final long serialVersionUID = 1L;
record Element(String name, String symbol, int number, double mass, boolean gas) { }
static final class ElementModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private static final String[] NAMES = {"Name", "Symbol", "Number", "Mass", "Gas"};
private static final Class<?>[] TYPES = {String.class, String.class, Integer.class, Double.class, Boolean.class};
private final ArrayList<Element> rows = new ArrayList<>();
ElementModel(List<Element> data) { rows.addAll(data); }
public int getRowCount() { return rows.size(); }
public int getColumnCount() { return NAMES.length; }
@Override public String getColumnName(int c) { return NAMES[c]; }
@Override public Class<?> getColumnClass(int c) { return TYPES[c]; }
public Object getValueAt(int r, int c) {
Element e = rows.get(r);
return switch (c) {
case 0 -> e.name(); case 1 -> e.symbol(); case 2 -> e.number();
case 3 -> e.mass(); default -> e.gas();
};
}
Element get(int modelRow) { return rows.get(modelRow); }
}
private final ElementModel model = new ElementModel(List.of(
new Element("Hydrogen", "H", 1, 1.008, true), new Element("Helium", "He", 2, 4.0026, true),
new Element("Carbon", "C", 6, 12.011, false), new Element("Nitrogen", "N", 7, 14.007, true),
new Element("Oxygen", "O", 8, 15.999, true), new Element("Neon", "Ne", 10, 20.180, true),
new Element("Sodium", "Na", 11, 22.990, false), new Element("Silicon", "Si", 14, 28.085, false),
new Element("Argon", "Ar", 18, 39.95, true), new Element("Iron", "Fe", 26, 55.845, false),
new Element("Copper", "Cu", 29, 63.546, false), new Element("Silver", "Ag", 47, 107.87, false),
new Element("Gold", "Au", 79, 196.97, false), new Element("Mercury", "Hg", 80, 200.59, false)));
private final JTable table = new JTable(model);
private final transient TableRowSorter<ElementModel> sorter = new TableRowSorter<>(model);
private final JTextField search = new JTextField(15);
private final JCheckBox gasesOnly = new JCheckBox("Gases only");
private final JLabel status = new JLabel();
public ElementTableFrame() {
super("Elements");
table.setRowSorter(sorter);
table.setFillsViewportHeight(true);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getColumnModel().getColumn(0).setPreferredWidth(140);
add(new JScrollPane(table), BorderLayout.CENTER);
var top = new JPanel(new FlowLayout(FlowLayout.LEADING));
top.add(new JLabel("Search:"));
top.add(search);
top.add(gasesOnly);
var print = new JButton("Print...");
print.addActionListener(_ -> {
try {
table.print(JTable.PrintMode.FIT_WIDTH);
} catch (PrinterException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage(), "Print", JOptionPane.ERROR_MESSAGE);
}
});
top.add(print);
add(top, BorderLayout.NORTH);
add(status, BorderLayout.SOUTH);
search.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) { updateFilter(); }
public void removeUpdate(DocumentEvent e) { updateFilter(); }
public void changedUpdate(DocumentEvent e) { }
});
gasesOnly.addActionListener(_ -> updateFilter());
sorter.addRowSorterListener(_ -> updateStatus());
table.getSelectionModel().addListSelectionListener(e -> {
if (!e.getValueIsAdjusting()) updateStatus();
});
// right-click on the header to hide or show columns
var columnMenu = new JPopupMenu();
TableColumnModel columns = table.getColumnModel();
List<TableColumn> all = new ArrayList<>();
for (int i = 0; i < columns.getColumnCount(); i++) all.add(columns.getColumn(i));
for (TableColumn column : all) {
var item = new JCheckBoxMenuItem(column.getHeaderValue().toString(), true);
item.addActionListener(_ -> {
if (item.isSelected()) table.addColumn(column);
else if (table.getColumnCount() > 1) table.removeColumn(column);
else item.setSelected(true); // keep at least one column
});
columnMenu.add(item);
}
table.getTableHeader().setComponentPopupMenu(columnMenu);
updateStatus();
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
}
private void updateFilter() {
List<RowFilter<ElementModel, Integer>> filters = new ArrayList<>();
String text = search.getText().strip();
if (!text.isEmpty()) // quote the text: the user types words, not regular expressions
filters.add(RowFilter.regexFilter("(?i)" + Pattern.quote(text), 0, 1));
if (gasesOnly.isSelected())
filters.add(new RowFilter<>() {
public boolean include(Entry<? extends ElementModel, ? extends Integer> entry) {
return (Boolean) entry.getValue(4);
}
});
sorter.setRowFilter(filters.isEmpty() ? null : RowFilter.andFilter(filters));
}
private void updateStatus() {
String text = table.getRowCount() + " of " + model.getRowCount() + " elements";
int viewRow = table.getSelectedRow();
if (viewRow >= 0) {
Element e = model.get(table.convertRowIndexToModel(viewRow)); // view index -> model index
text += " | selected: " + e.name() + " (" + e.symbol() + ", " + e.number() + ")";
}
status.setText(text);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new ElementTableFrame().setVisible(true));
}
}
The program
The demo works with tables that are never displayed, which is enough to exercise models, sorters, filters, column models and selection.
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.table.*;
public class Solution {
record Element(String name, String symbol, int number, double mass, boolean gas) { }
/** A table model backed by a list of records. */
static class ElementModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private static final String[] NAMES = {"Name", "Symbol", "Number", "Mass", "Gas"};
private static final Class<?>[] TYPES = {String.class, String.class, Integer.class, Double.class, Boolean.class};
private final ArrayList<Element> rows = new ArrayList<>();
ElementModel(List<Element> data) { rows.addAll(data); }
@Override public int getRowCount() { return rows.size(); }
@Override public int getColumnCount() { return NAMES.length; }
@Override public String getColumnName(int c) { return NAMES[c]; }
@Override public Class<?> getColumnClass(int c) { return TYPES[c]; }
@Override public Object getValueAt(int r, int c) {
Element e = rows.get(r);
return switch (c) {
case 0 -> e.name();
case 1 -> e.symbol();
case 2 -> e.number();
case 3 -> e.mass();
default -> e.gas();
};
}
@Override public boolean isCellEditable(int r, int c) { return c == 0; } // only the name
@Override public void setValueAt(Object value, int r, int c) {
Element e = rows.get(r);
rows.set(r, new Element((String) value, e.symbol(), e.number(), e.mass(), e.gas()));
fireTableCellUpdated(r, c);
}
void add(Element e) {
rows.add(e);
fireTableRowsInserted(rows.size() - 1, rows.size() - 1);
}
}
/** A model whose values are computed on demand: nothing is stored. */
static class ConversionModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
@Override public int getRowCount() { return 7; }
@Override public int getColumnCount() { return 3; }
@Override public Object getValueAt(int r, int c) {
double celsius = -20 + 10 * r;
double v = switch (c) { case 0 -> celsius; case 1 -> celsius * 9 / 5 + 32; default -> celsius + 273.15; };
return "%.2f".formatted(v);
}
@Override public String getColumnName(int c) { return new String[] {"Celsius", "Fahrenheit", "Kelvin"}[c]; }
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
Locale.setDefault(Locale.US);
EventQueue.invokeAndWait(Solution::run);
}
static void print(String title, JTable table) {
System.out.println(title);
int cols = table.getColumnCount();
StringBuilder header = new StringBuilder(" ");
for (int c = 0; c < cols; c++) header.append("%-11s".formatted(table.getColumnName(c)));
System.out.println(header.toString().stripTrailing());
for (int r = 0; r < table.getRowCount(); r++) {
StringBuilder line = new StringBuilder(" ");
for (int c = 0; c < cols; c++) line.append("%-11s".formatted(table.getValueAt(r, c)));
System.out.println(line.toString().stripTrailing());
}
}
static void run() {
var model = new ElementModel(List.of(
new Element("Hydrogen", "H", 1, 1.008, true),
new Element("Carbon", "C", 6, 12.011, false),
new Element("Neon", "Ne", 10, 20.180, true),
new Element("Iron", "Fe", 26, 55.845, false),
new Element("Argon", "Ar", 18, 39.95, true),
new Element("Gold", "Au", 79, 196.97, false)));
var table = new JTable(model);
System.out.println("== A table over a custom model ==");
print("model order", table);
System.out.println("column classes: " + Arrays.toString(new String[] {
table.getColumnClass(2).getSimpleName(), table.getColumnClass(4).getSimpleName()}));
System.out.println("renderer for Boolean: " + table.getDefaultRenderer(Boolean.class).getClass().getSimpleName()
.replace("JTable$", ""));
System.out.println("editable: name " + table.isCellEditable(0, 0) + ", mass " + table.isCellEditable(0, 3));
System.out.println();
System.out.println("== Model events ==");
model.addTableModelListener(e -> System.out.println(" event: " + switch (e.getType()) {
case TableModelEvent.INSERT -> "INSERT";
case TableModelEvent.DELETE -> "DELETE";
default -> "UPDATE";
} + " rows " + e.getFirstRow() + ".." + e.getLastRow() + ", column " + e.getColumn()));
model.add(new Element("Oxygen", "O", 8, 15.999, true));
table.setValueAt("Aurum", 5, 0); // as if the user edited the cell
System.out.println("row count now " + table.getRowCount() + ", row 5 is " + model.getValueAt(5, 0));
System.out.println();
System.out.println("== Sorting with a TableRowSorter ==");
var sorter = new TableRowSorter<ElementModel>(model);
table.setRowSorter(sorter);
sorter.setSortKeys(List.of(new RowSorter.SortKey(3, SortOrder.DESCENDING)));
print("by mass, descending", table);
sorter.setComparator(1, Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
sorter.setSortKeys(List.of(new RowSorter.SortKey(4, SortOrder.DESCENDING),
new RowSorter.SortKey(1, SortOrder.ASCENDING)));
print("gases first, then by symbol length and symbol", table);
System.out.println("view row 0 is model row " + table.convertRowIndexToModel(0)
+ "; model row 0 is view row " + table.convertRowIndexToView(0));
System.out.println();
System.out.println("== Filtering ==");
sorter.setSortKeys(List.of(new RowSorter.SortKey(2, SortOrder.ASCENDING)));
sorter.setRowFilter(RowFilter.numberFilter(RowFilter.ComparisonType.AFTER, 9, 2));
print("atomic number after 9", table);
System.out.println("view rows " + table.getRowCount() + ", model rows " + model.getRowCount());
sorter.setRowFilter(RowFilter.andFilter(List.of(
RowFilter.regexFilter("(?i)^[a-h]", 0),
RowFilter.notFilter(RowFilter.regexFilter("true", 4)))));
print("name starts with A-H and not a gas", table);
sorter.setRowFilter(new RowFilter<ElementModel, Integer>() {
@Override public boolean include(Entry<? extends ElementModel, ? extends Integer> entry) {
return (Integer) entry.getValue(2) % 2 == 0; // even atomic numbers
}
});
print("custom filter: even atomic numbers", table);
sorter.setRowFilter(null);
System.out.println();
System.out.println("== Columns: move, hide, show, widths ==");
TableColumnModel columns = table.getColumnModel();
table.moveColumn(1, 0); // Symbol first (view only)
TableColumn gas = columns.getColumn(4);
table.removeColumn(gas); // hidden, still in the model
System.out.println("view columns " + table.getColumnCount() + ", model columns " + model.getColumnCount());
System.out.println("view column 0 shows model column " + table.convertColumnIndexToModel(0)
+ " (" + model.getColumnName(table.convertColumnIndexToModel(0)) + ")");
table.addColumn(gas);
table.addColumn(new TableColumn(2)); // a second view of the Number column
StringBuilder names = new StringBuilder();
for (int c = 0; c < table.getColumnCount(); c++) names.append(table.getColumnName(c)).append(' ');
System.out.println("columns now: " + names.toString().strip());
columns.getColumn(1).setPreferredWidth(150);
columns.getColumn(0).setMaxWidth(40);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setSize(table.getPreferredSize());
table.doLayout();
System.out.println("widths with AUTO_RESIZE_OFF: " + widths(table) + ", table width " + table.getWidth());
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setSize(400, table.getHeight());
table.doLayout();
System.out.println("widths at 400 with AUTO_RESIZE_ALL_COLUMNS: " + widths(table));
System.out.println();
System.out.println("== Selection ==");
table.setRowSelectionInterval(1, 2);
table.addRowSelectionInterval(4, 4);
System.out.println("selected view rows " + Arrays.toString(table.getSelectedRows())
+ " = model rows " + Arrays.toString(Arrays.stream(table.getSelectedRows())
.map(table::convertRowIndexToModel).toArray()));
table.setCellSelectionEnabled(true);
table.changeSelection(0, 1, false, false);
table.changeSelection(1, 2, false, true); // shift-click extends
System.out.println("cell selection: rows " + Arrays.toString(table.getSelectedRows())
+ ", columns " + Arrays.toString(table.getSelectedColumns()));
System.out.println("row height " + table.getRowHeight() + ", row margin " + table.getRowMargin());
System.out.println();
System.out.println("== A computed model ==");
print("temperature conversions", new JTable(new ConversionModel()));
var plain = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
public int getRowCount() { return 0; }
public int getColumnCount() { return 3; }
public Object getValueAt(int r, int c) { return null; }
};
System.out.println("default column names: " + plain.getColumnName(0) + ", " + plain.getColumnName(1)
+ ", " + plain.getColumnName(2) + "; editable by default: " + plain.isCellEditable(0, 0)
+ " (DefaultTableModel: " + new DefaultTableModel(1, 1).isCellEditable(0, 0) + ")");
}
static String widths(JTable table) {
int[] w = new int[table.getColumnCount()];
for (int c = 0; c < w.length; c++) w[c] = table.getColumnModel().getColumn(c).getWidth();
return Arrays.toString(w);
}
}
== A table over a custom model ==
model order
Name Symbol Number Mass Gas
Hydrogen H 1 1.008 true
Carbon C 6 12.011 false
Neon Ne 10 20.18 true
Iron Fe 26 55.845 false
Argon Ar 18 39.95 true
Gold Au 79 196.97 false
column classes: [Integer, Boolean]
renderer for Boolean: BooleanRenderer
editable: name true, mass false
== Model events ==
event: INSERT rows 6..6, column -1
event: UPDATE rows 5..5, column 0
row count now 7, row 5 is Aurum
== Sorting with a TableRowSorter ==
by mass, descending
Name Symbol Number Mass Gas
Aurum Au 79 196.97 false
Iron Fe 26 55.845 false
Argon Ar 18 39.95 true
Neon Ne 10 20.18 true
Oxygen O 8 15.999 true
Carbon C 6 12.011 false
Hydrogen H 1 1.008 true
gases first, then by symbol length and symbol
Name Symbol Number Mass Gas
Hydrogen H 1 1.008 true
Oxygen O 8 15.999 true
Argon Ar 18 39.95 true
Neon Ne 10 20.18 true
Carbon C 6 12.011 false
Aurum Au 79 196.97 false
Iron Fe 26 55.845 false
view row 0 is model row 0; model row 0 is view row 0
== Filtering ==
atomic number after 9
Name Symbol Number Mass Gas
Neon Ne 10 20.18 true
Argon Ar 18 39.95 true
Iron Fe 26 55.845 false
Aurum Au 79 196.97 false
view rows 4, model rows 7
name starts with A-H and not a gas
Name Symbol Number Mass Gas
Carbon C 6 12.011 false
Aurum Au 79 196.97 false
custom filter: even atomic numbers
Name Symbol Number Mass Gas
Carbon C 6 12.011 false
Oxygen O 8 15.999 true
Neon Ne 10 20.18 true
Argon Ar 18 39.95 true
Iron Fe 26 55.845 false
== Columns: move, hide, show, widths ==
view columns 4, model columns 5
view column 0 shows model column 1 (Symbol)
columns now: Symbol Name Number Mass Gas Number
widths with AUTO_RESIZE_OFF: [40, 150, 75, 75, 75, 75], table width 490
widths at 400 with AUTO_RESIZE_ALL_COLUMNS: [34, 120, 62, 61, 62, 61]
== Selection ==
selected view rows [1, 2, 4] = model rows [1, 6, 4]
cell selection: rows [0, 1], columns [1, 2]
row height 16, row margin 1
== A computed model ==
temperature conversions
Celsius Fahrenheit Kelvin
-20.00 -4.00 253.15
-10.00 14.00 263.15
0.00 32.00 273.15
10.00 50.00 283.15
20.00 68.00 293.15
30.00 86.00 303.15
40.00 104.00 313.15
default column names: A, B, C; editable by default: false (DefaultTableModel: true)
Points to notice:
- The row inserted by the model's
addmethod fired anINSERTevent with column -1 (all columns);table.setValueAt, which is what an editor calls, reached the model'ssetValueAt, which fired anUPDATEfor one cell. - The model's rows never moved; sorting and filtering only changed the view, and
convertRowIndexToModeltranslated between them. - The regex filter used
(?i)for case-insensitivity, andnotFilterexcluded the gases. The custom filter read cell values through theEntry. - A hidden column disappeared from the view (4 view columns) but not from the model (5 columns), and a second
TableColumnshowed the Number column twice.
Common questions
Why does my table show "true"/"false" instead of check boxes, or sort numbers as text?
The model's getColumnClass returns Object.class. Override it to return Boolean.class, Integer.class and so on, and the table picks the matching renderer, editor and comparator.
I selected a row, but I'm reading the wrong record. Why?
After sorting or filtering, view and model indexes differ. Convert with table.convertRowIndexToModel(viewRow) before accessing your model or list.
Why doesn't my table update when I change the data?
The model must fire an event: fireTableRowsInserted, fireTableRowsUpdated, fireTableCellUpdated or fireTableDataChanged, on the EDT. Changing the underlying list alone isn't enough.
How do I make some cells read-only?
Override isCellEditable(row, column) in the model to return false for them. Note that DefaultTableModel returns true for every cell by default.
How do I export a table to CSV?
Iterate over the view (table.getRowCount(), getColumnCount(), getValueAt) to export what the user sees, or over the model to export all data, quoting fields that contain commas, quotes or newlines.
How do I show millions of rows?
Implement a model that computes or fetches rows on demand instead of storing them; the table only asks for visible cells. Sorting and filtering with TableRowSorter then touches every row, so for very large data, sort and filter in the database instead.
API reference
| Class / method | Purpose |
|---|---|
JTable(cells, columnNames), JTable(model), setAutoCreateRowSorter, setFillsViewportHeight, print | Creating tables. |
TableModel.getRowCount/getColumnCount/getValueAt/setValueAt/isCellEditable/getColumnName/getColumnClass | The model interface. |
AbstractTableModel.fireTableCellUpdated/RowsInserted/RowsDeleted/RowsUpdated/DataChanged/StructureChanged, addTableModelListener | Model events. |
DefaultTableModel.addRow, insertRow, removeRow, addColumn | Ready-made mutable model. |
JTable.getColumnModel, TableColumnModel.getColumn, TableColumn.getModelIndex, setPreferredWidth/MinWidth/MaxWidth/Resizable | Columns. |
JTable.removeColumn, addColumn, moveColumn, setAutoResizeMode | Column view operations. |
JTable.setRowHeight(height), setRowHeight(row, height), setRowMargin | Row heights. |
getSelectionModel().setSelectionMode, setRowSelectionAllowed, setColumnSelectionAllowed, setCellSelectionEnabled, getSelectedRows, getSelectedColumns | Selection. |
convertRowIndexToModel/ToView, convertColumnIndexToModel/ToView | View and model indexes. |
TableRowSorter(model), setRowSorter, setComparator, setSortable, setSortKeys, setSortsOnUpdates, setStringConverter, sort | Sorting. |
RowFilter.numberFilter/dateFilter/regexFilter/andFilter/orFilter/notFilter, include(Entry), DefaultRowSorter.setRowFilter | Filtering. |
Summary
JTabledisplays a model's data; put it in a scroll pane for headers and scrolling. Users can move and resize columns, select, sort and edit out of the box.- Implement
AbstractTableModel(row count, column count,getValueAt), add column names and classes, and fire the matching event after every change. Editing requiresisCellEditableandsetValueAt. - Columns are
TableColumnobjects in aTableColumnModel; hide them withremoveColumnand control widths and the auto-resize mode. Row heights and selection modes are set on the table. - Indexes from the table are view indexes; convert them with
convertRowIndexToModelandconvertColumnIndexToModelbefore using the model. TableRowSortersorts with collators,Comparableor custom comparators, and filters withRowFilters, which can be combined or written from scratch.
Practice Questions
1. A table shows numbers, but clicking the column header sorts them as "1, 10, 2, 26, 6". What is missing?
The model's getColumnClass returns Object.class (the default) for that column, so the sorter compares the values' strings with the collator. Override getColumnClass to return Integer.class (or the actual numeric class); the sorter then uses compareTo and sorts numerically, and the renderer right-aligns the numbers.
2. After the user sorts a table, the program deletes the wrong record when the user selects a row and clicks Delete. Why?
getSelectedRow returns a view index, which differs from the model index once the rows are sorted or filtered. The program used it directly on the model. Convert it first with table.convertRowIndexToModel(viewRow), then delete that model row and fire fireTableRowsDeleted.
3. A model adds a record to its list, but the table does not show the new row until the window is resized. What did the model forget?
It did not fire an event. After changing the data, a model must notify its listeners, here with fireTableRowsInserted(index, index). The table and its sorter are listeners; they update their row count and repaint when they receive the event.
4. Why does RowFilter.numberFilter(ComparisonType.AFTER, 100, 3) hide a row whose column 3 is 100.7?
The argument 100 is an Integer and the cells are Doubles. When the classes differ, the filter compares longValue()s, and 100.7 becomes 100, which is not after 100. Pass 100.0 so that the doubles are compared exactly.
5. How do you temporarily hide a table column, and how do you show it again?
Get its TableColumn from the column model, keep a reference to it, and call table.removeColumn(column). The data stays in the model. To show it again, call table.addColumn(column), which appends it at the end, and if necessary moveColumn to put it back at its original position.
Previous: Swing Dialogs: JOptionPane, Custom Dialogs and JFileChooser
Next: Swing Table Cell Renderers and Editors: Custom Rendering and Editing
Related reading
- Swing Dialogs: JOptionPane, Custom Dialogs and JFileChooser
- GridBagLayout and Custom Layout Managers in Swing
- Swing Menus, Toolbars and Tooltips: Mnemonics, Accelerators and Popup Menus
- Swing Choice Components: Check Boxes, Radio Buttons, Borders, Combo Boxes and Sliders
- Swing Text Components: Text Fields, Labels, Password Fields and Text Areas

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.