Swing Table Cell Renderers and Editors: Custom Rendering and Editing
How JTable draws and edits its cells: default renderers by column class, custom renderers as rubber stamps, header renderers, the default text, check box and combo box editors, validating input, and writing your own cell editor with AbstractCellEditor.
kvi5hnuCode Sprout team member12 min readOn this page
The previous article was about a table's data. This one is about its cells: how they are drawn, and how the user changes them. Both are pluggable. A renderer draws cells, and an editor provides the component the user types into or clicks. Swing chooses defaults based on the column class, and you can replace either for a whole class of values or for one column.

Rendering cells
A table with a thousand rows does not contain a thousand labels. Instead, a renderer works like a rubber stamp: for each visible cell, the table calls the renderer's single method,
Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
and the renderer returns a component configured for that cell (its text, colors and border). The table paints that component into the cell rectangle and moves on to the next cell, usually getting the same component object back, reconfigured. The demo confirms that the renderer returned one and the same component for two different rows. It also fell into the classic trap: holding on to a returned component and calling the renderer again changes the component you are holding. Use the component right away.
Three consequences follow. The renderer must set every property it uses on each call, because the component still carries the settings of the previous cell. The component is never really part of the table, so it cannot react to mouse clicks; a button drawn by a renderer is only a picture of a button. And the method must be fast, since it runs for every visible cell on every repaint.
Default renderers
The table picks a renderer by the column class that the model reports (getColumnClass). The demo prints what the default renderers produce:
| Column class | Default renderer |
|---|---|
Object, String | a label with toString(), left-aligned |
Number, Integer | a right-aligned label |
Double, Float | a right-aligned label, formatted for the locale |
Date | a label with a locale-formatted date |
Boolean | a check box |
Icon, ImageIcon | a label with the image |
A Color column falls back to the Object renderer and shows text like java.awt.Color[r=255,g=200,b=0], which is why a custom renderer is needed.
Writing a renderer
For anything drawn as text or an icon, extend DefaultTableCellRenderer, a JLabel subclass that already handles selection colors, focus borders and tooltips. Usually, you only override setValue:
class HoursRenderer extends DefaultTableCellRenderer {
HoursRenderer() { setHorizontalAlignment(RIGHT); }
@Override protected void setValue(Object value) {
double h = (Double) value;
setText(h >= 8 ? "%.1f days".formatted(h / 8) : "%.2f h".formatted(h));
}
}
For graphics, implement TableCellRenderer with any component. The color swatch renderer extends JPanel and sets its background:
class ColorRenderer extends JPanel implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
setBackground((Color) value);
setBorder(hasFocus ? UIManager.getBorder("Table.focusCellHighlightBorder") : null);
return this;
}
}
The isSelected and hasFocus parameters let the renderer show selection and focus; the UIManager key gives the look and feel's focus border. The demo paints its swatch renderer into an offscreen image and reads the center pixel to confirm that each row is drawn in its own color.
Installing renderers
Choose the scope:
table.setDefaultRenderer(Color.class, renderer)uses the renderer for every column whose class isColor(or a subclass, if no more specific renderer is registered).column.setCellRenderer(renderer)uses it for oneTableColumn, regardless of class.- To decide per cell (say, a different renderer for a total row), subclass
JTableand overridegetCellRenderer(row, column).
To change the appearance of all cells, such as zebra-striped rows or graying out finished tasks, override JTable.prepareRenderer. It calls the renderer and then lets you adjust the returned component, whichever renderer produced it. The listing at the end uses it for stripes.
Renderers are also responsible for tooltips: a renderer component's setToolTipText is shown when the mouse rests over that cell, because JTable.getToolTipText(MouseEvent) asks the renderer for each cell.
Rendering the header
The header cell of a column shows its header value, which defaults to the model's column name: column.setHeaderValue("Prio") changes the label without changing the model, as the demo shows. A header renderer draws it; column.setHeaderRenderer(renderer) replaces the renderer for one column, for instance to show an icon (table.getDefaultRenderer(Icon.class) with an Icon header value). To keep the look and feel's header style and sort arrows, wrap the default table.getTableHeader().getDefaultRenderer() and adjust the component it returns rather than writing a header renderer from scratch.
Editing cells
For a cell to be editable, two things are needed: the model's isCellEditable(row, column) returns true, and an editor exists for it. The editor's component is placed over the cell while the user edits; when editing stops, the table passes the editor's value to the model's setValueAt.
Default editors
JTable installs editors for its default column classes, all instances of DefaultCellEditor, which can wrap a JTextField, a JCheckBox or a JComboBox:
Booleancolumns get a check box editor: one click toggles the value.- Other editable cells get a text field. For
Numbercolumns the generic editor converts the text back to the column class by calling its constructor with aString(Integer("42"),Double("5.5")). If that fails,stopCellEditingreturnsfalse: the cell gets a red border and the editor stays open, as the demo shows when it enters "lots" into aDoublecolumn. For anObjectcolumn,setValueAtreceives the string.
Editing starts on a double click, or when the user starts typing in a focused cell. Enter or Tab commits, Escape cancels.
A combo box editor
The table cannot know which values are valid for a column, so a combo box editor must be installed explicitly, usually for one column:
var priorities = new JComboBox<Integer>(new Integer[] {1, 2, 3, 4, 5});
table.getColumnModel().getColumn(PRIORITY).setCellEditor(new DefaultCellEditor(priorities));
The combo box starts with the cell's current value selected, and choosing an item ends the editing. The value passed to setValueAt is the selected item, here an Integer, so no conversion is needed.
The type of the value that reaches setValueAt depends on the editor: a Boolean from a check box, the selected object from a combo box, and for a text field either a converted number (generic editor) or a String. A model that accepts edits should check the type, and convert or reject values as needed.
Validating input
To restrict what users can enter in a text cell, subclass DefaultCellEditor and override stopCellEditing: return false to keep the editor open when the input is invalid, and call super.stopCellEditing() otherwise. Override getCellEditorValue to return a converted value instead of the raw string. The listing's hours editor does both, refusing negative numbers.
A related nuisance: if the user is still editing a cell when they click Save in a toolbar, the edit has not reached the model yet. Before saving, call table.getCellEditor().stopCellEditing() when table.isEditing() is true (and abort the save if it returns false). The client property table.putClientProperty("terminateEditOnFocusLost", true) makes the table commit an edit when the focus moves to another component.
Writing your own editor
For other editors (a spinner, a date picker, a color chooser), implement TableCellEditor. Its getTableCellEditorComponent(table, value, isSelected, row, column) method returns the component placed over the cell, configured with the current value. The rest of the interface comes from CellEditor:
| Method | Purpose |
|---|---|
isCellEditable(EventObject e) | Does this event (a mouse click, a key) start editing? |
shouldSelectCell(EventObject e) | Should the cell become selected when editing starts? |
stopCellEditing() | Finish editing and keep the value; return false to refuse. |
cancelCellEditing() | Abandon the edit. |
getCellEditorValue() | The value the edit produced. |
addCellEditorListener, removeCellEditorListener | Notify the table when editing stops or is canceled. |
AbstractCellEditor implements the listener bookkeeping and sensible defaults (isCellEditable and shouldSelectCell return true, stopCellEditing fires editingStopped, cancelCellEditing fires editingCanceled), so an in-place editor needs only two methods:
class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
private final JSpinner spinner = new JSpinner(new SpinnerNumberModel(1.0, 0.0, 100.0, 0.25));
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
spinner.setValue(value);
return spinner;
}
public Object getCellEditorValue() { return spinner.getValue(); }
}
If you override stopCellEditing or cancelCellEditing, call the superclass method, or the table never learns that editing ended. The table listens to the editor's events: on editingStopped it calls getCellEditorValue and the model's setValueAt, and on editingCanceled it simply removes the editor component. The demo's listener sees both events, and the canceled value never reaches the model.
Some editors are better as dialogs: clicking a color cell to open a JColorChooser, for example. Then the component returned for the cell is only a placeholder (a button or plain panel); the editor opens the dialog and, when the user confirms or cancels, calls stopCellEditing or cancelCellEditing itself. Override isCellEditable to require a double click, so that a single click only selects the cell. The listing does this with JColorChooser.showDialog, deferred with invokeLater until the table has installed the placeholder.
A task table
The following program puts the pieces together: a swatch renderer and a dialog-based color editor for the Color column, a formatting renderer and a validating, converting text editor for the hours, a combo box editor for the priority, zebra stripes through prepareRenderer, and a Save button that first commits any edit in progress.
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.EventObject;
import javax.swing.*;
import javax.swing.table.*;
public final class TaskTableFrame extends JFrame {
private static final long serialVersionUID = 1L;
static final class TaskModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private static final String[] NAMES = {"Task", "Priority", "Done", "Label", "Hours"};
private static final Class<?>[] TYPES = {String.class, Integer.class, Boolean.class, Color.class, Double.class};
private final transient Object[][] cells = {
{"Write outline", 2, true, Color.GREEN, 1.5},
{"Draw diagrams", 3, false, Color.ORANGE, 4.25},
{"Review code", 1, false, Color.RED, 12.0},
{"Publish", 5, false, Color.CYAN, 0.5},
};
public int getRowCount() { return cells.length; }
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) { return cells[r][c]; }
@Override public boolean isCellEditable(int r, int c) { return true; }
@Override public void setValueAt(Object value, int r, int c) {
cells[r][c] = value;
fireTableCellUpdated(r, c);
}
}
static final class ColorRenderer extends JPanel implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
setBackground((Color) value);
setBorder(BorderFactory.createMatteBorder(3, 3, 3, 3,
isSelected ? table.getSelectionBackground() : table.getBackground()));
setToolTipText("Double-click to change the color");
return this;
}
}
static final class HoursRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
HoursRenderer() { setHorizontalAlignment(RIGHT); }
@Override protected void setValue(Object value) {
double h = (Double) value;
setText(h >= 8 ? "%.1f days".formatted(h / 8) : "%.2f h".formatted(h));
}
}
/** Opens a color chooser dialog; the cell shows a plain button while the dialog is up. */
static final class ColorEditor extends AbstractCellEditor implements TableCellEditor {
private static final long serialVersionUID = 1L;
private final JButton button = new JButton();
private Color current;
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
current = (Color) value;
button.setBackground(current);
// show the dialog after the table has installed the editor component
EventQueue.invokeLater(() -> {
Color chosen = JColorChooser.showDialog(table, "Label color", current);
if (chosen != null) {
current = chosen;
stopCellEditing();
} else {
cancelCellEditing();
}
});
return button;
}
public Object getCellEditorValue() { return current; }
@Override public boolean isCellEditable(EventObject e) {
return !(e instanceof MouseEvent m) || m.getClickCount() >= 2; // double-click to edit
}
}
public TaskTableFrame() {
super("Tasks");
var table = new JTable(new TaskModel()) {
private static final long serialVersionUID = 1L;
// zebra stripes: adjust whatever component the renderer returned
@Override public Component prepareRenderer(TableCellRenderer r, int row, int column) {
Component c = super.prepareRenderer(r, row, column);
if (!isRowSelected(row) && !(c instanceof ColorRenderer))
c.setBackground(row % 2 == 0 ? getBackground() : new Color(0xF2F5FA));
return c;
}
};
table.setDefaultRenderer(Color.class, new ColorRenderer());
table.setDefaultEditor(Color.class, new ColorEditor());
TableColumnModel columns = table.getColumnModel();
columns.getColumn(4).setCellRenderer(new HoursRenderer());
columns.getColumn(4).setCellEditor(new DefaultCellEditor(new JTextField()) {
private static final long serialVersionUID = 1L;
@Override public Object getCellEditorValue() { // convert the text to a Double
return Double.valueOf(super.getCellEditorValue().toString().strip());
}
@Override public boolean stopCellEditing() {
try {
double h = Double.parseDouble(super.getCellEditorValue().toString().strip());
if (h < 0) return false; // reject: editing continues
} catch (NumberFormatException e) {
return false;
}
return super.stopCellEditing();
}
});
var priorities = new JComboBox<Integer>(new Integer[] {1, 2, 3, 4, 5});
columns.getColumn(1).setCellEditor(new DefaultCellEditor(priorities));
columns.getColumn(0).setPreferredWidth(180);
table.setRowHeight(table.getRowHeight() + 6);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); // commit when focus leaves
table.setFillsViewportHeight(true);
add(new JScrollPane(table));
var save = new JButton("Save");
save.addActionListener(_ -> {
if (table.isEditing() && !table.getCellEditor().stopCellEditing()) return; // finish edits first
JOptionPane.showMessageDialog(this, "Saved " + table.getRowCount() + " tasks");
});
var south = new JPanel();
south.add(save);
add(south, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new TaskTableFrame().setVisible(true));
}
}
The program
The demo uses a table that is never shown. It asks the table to prepare renderers for cells and inspects the resulting components, paints a renderer into an image, and drives editing from code with editCellAt, which installs the editor exactly as a double click would, followed by stopCellEditing or cancelCellEditing.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import java.util.Locale;
import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.*;
public class Solution {
static final String[] NAMES = {"Task", "Priority", "Done", "Label", "Hours"};
static final Class<?>[] TYPES = {String.class, Integer.class, Boolean.class, Color.class, Double.class};
static class TaskModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private final transient Object[][] cells = {
{"Write outline", 2, true, Color.GREEN, 1.5},
{"Draw diagrams", 3, false, Color.ORANGE, 4.25},
{"Review code", 1, false, Color.RED, 12.0},
};
final transient List<String> log = new ArrayList<>();
public int getRowCount() { return cells.length; }
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) { return cells[r][c]; }
@Override public boolean isCellEditable(int r, int c) { return c != 3; }
@Override public void setValueAt(Object v, int r, int c) {
log.add("setValueAt(" + v + " : " + v.getClass().getSimpleName() + ", row " + r + ", col " + c + ")");
cells[r][c] = v;
fireTableCellUpdated(r, c);
}
}
/** Draws the cell's color as a swatch; one component is reused for every cell. */
static class ColorRenderer extends JPanel implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
setBackground((Color) value);
setBorder(hasFocus ? UIManager.getBorder("Table.focusCellHighlightBorder")
: BorderFactory.createLineBorder(table.getBackground(), 2));
return this;
}
}
/** Text renderers: subclass DefaultTableCellRenderer and override setValue. */
static class HoursRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
HoursRenderer() { setHorizontalAlignment(RIGHT); }
@Override protected void setValue(Object value) {
double h = (Double) value;
setText(h >= 8 ? "%.1f d".formatted(h / 8) : "%.2f h".formatted(h));
}
}
/** An in-place editor with a spinner, built on AbstractCellEditor. */
static class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
private static final long serialVersionUID = 1L;
final JSpinner spinner = new JSpinner(new SpinnerNumberModel(1.0, 0.0, 100.0, 0.25));
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
spinner.setValue(value); // start from the current value
return spinner;
}
public Object getCellEditorValue() { return spinner.getValue(); }
@Override public boolean isCellEditable(EventObject e) { return true; }
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
Locale.setDefault(Locale.US);
EventQueue.invokeAndWait(Solution::run);
}
static String describe(Component c) {
if (c instanceof JCheckBox b) return "JCheckBox selected=" + b.isSelected();
if (c instanceof JLabel l) {
String align = switch (l.getHorizontalAlignment()) {
case SwingConstants.RIGHT -> "right"; case SwingConstants.CENTER -> "center"; default -> "left/leading";
};
return "JLabel \"" + l.getText() + "\" " + align;
}
return c.getClass().getSimpleName();
}
static void run() {
var model = new TaskModel();
var table = new JTable(model);
table.setSize(500, 200);
table.doLayout();
System.out.println("== Default renderers chosen by column class ==");
for (int c = 0; c < model.getColumnCount(); c++) {
Component comp = table.prepareRenderer(table.getCellRenderer(1, c), 1, c);
System.out.printf(" %-8s %-8s -> %s%n", NAMES[c], TYPES[c].getSimpleName(), describe(comp));
}
System.out.println();
System.out.println("== Custom renderers ==");
table.setDefaultRenderer(Color.class, new ColorRenderer()); // for every Color column
table.getColumnModel().getColumn(4).setCellRenderer(new HoursRenderer()); // for one column
for (int r = 0; r < model.getRowCount(); r++) {
Component hours = table.prepareRenderer(table.getCellRenderer(r, 4), r, 4);
Component label = table.prepareRenderer(table.getCellRenderer(r, 3), r, 3);
System.out.printf(" row %d: hours %-14s label swatch %s%n", r, describe(hours), swatch(label, 30, 12));
}
Component a = table.prepareRenderer(table.getCellRenderer(0, 3), 0, 3);
Component b = table.prepareRenderer(table.getCellRenderer(2, 3), 2, 3);
System.out.println("same renderer component for rows 0 and 2: " + (a == b) + " (a rubber stamp)");
table.setRowSelectionInterval(1, 1);
Color selectedBg = table.prepareRenderer(table.getCellRenderer(1, 0), 1, 0).getBackground();
Color normalBg = table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0).getBackground();
System.out.println("selected row uses selection background: " + selectedBg.equals(table.getSelectionBackground())
+ ", unselected row uses table background: " + normalBg.equals(table.getBackground()));
table.clearSelection();
TableColumn priority = table.getColumnModel().getColumn(1);
priority.setHeaderValue("Prio");
System.out.println("header value now \"" + priority.getHeaderValue() + "\", table.getColumnName(1) = \""
+ table.getColumnName(1) + "\"");
System.out.println();
System.out.println("== Editing with the default editors ==");
System.out.println("default editors: Object -> " + editorKind(table.getDefaultEditor(Object.class))
+ ", Number -> " + editorKind(table.getDefaultEditor(Number.class))
+ ", Boolean -> " + editorKind(table.getDefaultEditor(Boolean.class)));
table.editCellAt(0, 0);
var field = (JTextField) table.getEditorComponent();
field.setText("Write the outline");
table.getCellEditor().stopCellEditing();
TableColumn hoursColumn = table.getColumnModel().getColumn(4);
hoursColumn.setCellEditor(table.getDefaultEditor(Double.class));
table.editCellAt(1, 4);
var numberField = (JTextField) table.getEditorComponent();
System.out.println("number editor starts with \"" + numberField.getText() + "\"");
numberField.setText("lots");
boolean stopped = table.getCellEditor().stopCellEditing();
System.out.println("stop with \"lots\": " + stopped + ", still editing: " + table.isEditing()
+ ", border is red: " + ((javax.swing.border.LineBorder) numberField.getBorder()).getLineColor().equals(Color.RED));
numberField.setText("5.5");
System.out.println("stop with \"5.5\": " + table.getCellEditor().stopCellEditing());
System.out.println();
System.out.println("== A combo box editor for one column ==");
var combo = new JComboBox<Integer>(new Integer[] {1, 2, 3, 4, 5});
priority.setCellEditor(new DefaultCellEditor(combo));
table.editCellAt(2, 1);
System.out.println("editor component: " + table.getEditorComponent().getClass().getSimpleName()
+ ", preselected " + combo.getSelectedItem());
combo.setSelectedItem(4); // with a combo box editor, choosing an item ends the edit
System.out.println("editing after choosing: " + table.isEditing());
System.out.println();
System.out.println("== A custom spinner editor ==");
var spinnerEditor = new SpinnerEditor();
spinnerEditor.addCellEditorListener(new CellEditorListener() {
public void editingStopped(ChangeEvent e) { System.out.println(" listener: editing stopped"); }
public void editingCanceled(ChangeEvent e) { System.out.println(" listener: editing canceled"); }
});
hoursColumn.setCellEditor(spinnerEditor);
table.editCellAt(0, 4);
spinnerEditor.spinner.setValue(2.75);
table.getCellEditor().stopCellEditing();
table.editCellAt(2, 4);
spinnerEditor.spinner.setValue(99.0);
table.getCellEditor().cancelCellEditing(); // like pressing Escape
System.out.println("row 2 hours unchanged: " + model.getValueAt(2, 4));
System.out.println();
System.out.println("model received:");
model.log.forEach(s -> System.out.println(" " + s));
}
static String editorKind(TableCellEditor e) {
return e instanceof DefaultCellEditor d ? d.getComponent().getClass().getSimpleName() : e.getClass().getSimpleName();
}
/** Paints the renderer component offscreen and reports the color at its center. */
static String swatch(Component c, int w, int h) {
var image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
c.setSize(w, h);
Graphics2D g = image.createGraphics();
c.paint(g);
g.dispose();
return "#%06X".formatted(image.getRGB(w / 2, h / 2) & 0xFFFFFF);
}
}
== Default renderers chosen by column class ==
Task String -> JLabel "Draw diagrams" left/leading
Priority Integer -> JLabel "3" right
Done Boolean -> JCheckBox selected=false
Label Color -> JLabel "java.awt.Color[r=255,g=200,b=0]" left/leading
Hours Double -> JLabel "4.25" right
== Custom renderers ==
row 0: hours JLabel "1.50 h" right label swatch #00FF00
row 1: hours JLabel "4.25 h" right label swatch #FFC800
row 2: hours JLabel "1.5 d" right label swatch #FF0000
same renderer component for rows 0 and 2: true (a rubber stamp)
selected row uses selection background: true, unselected row uses table background: true
header value now "Prio", table.getColumnName(1) = "Priority"
== Editing with the default editors ==
default editors: Object -> JTextField, Number -> JTextField, Boolean -> JCheckBox
number editor starts with "4.25"
stop with "lots": false, still editing: true, border is red: true
stop with "5.5": true
== A combo box editor for one column ==
editor component: JComboBox, preselected 1
editing after choosing: false
== A custom spinner editor ==
listener: editing stopped
listener: editing canceled
row 2 hours unchanged: 12.0
model received:
setValueAt(Write the outline : String, row 0, col 0)
setValueAt(5.5 : Double, row 1, col 4)
setValueAt(4 : Integer, row 2, col 1)
setValueAt(2.75 : Double, row 0, col 4)
Points to notice:
- The
Colorcolumn showedtoStringtext until a renderer was registered forColor.class. - The hours renderer, installed on one column, formatted 12 hours as "1.5 d" while the model still held
12.0. - The numeric editor refused "lots" (red border, still editing) and turned "5.5" into a
Double, which is what the model received. - The combo box editor delivered an
Integer, and selecting an item ended editing at once. - After
cancelCellEditing, the spinner's value 99.0 never reached the model.
Common questions
Why do all cells look like the last one I configured? Renderers reuse one component. Set every property (text, icon, colors, font, tooltip) on each call, including resetting values for cells that don't need them.
How do I put a clickable button in a table cell?
A renderer only paints a picture of a button. Combine a button renderer with an editor that returns a real JButton, and perform the action in the editor's listener, then call stopCellEditing(). Alternatively, handle clicks with a mouse listener on the table using rowAtPoint and columnAtPoint.
How do I color a whole row based on its data?
Override JTable.prepareRenderer: call super.prepareRenderer, read the row's data through convertRowIndexToModel, and set the component's background (keeping the selection color for selected rows).
My edit is lost when I click Save. Why?
The cell is still being edited, so the value hasn't reached the model. Call table.getCellEditor().stopCellEditing() first when table.isEditing(), or set the client property terminateEditOnFocusLost.
How do I start editing with a single click?
For DefaultCellEditor, call setClickCountToStart(1). For a custom editor, override isCellEditable(EventObject) to check the click count.
API reference
| Class / method | Purpose |
|---|---|
TableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) | Draw a cell. |
DefaultTableCellRenderer, setValue, setHorizontalAlignment | Label-based renderer. |
JTable.setDefaultRenderer(class, r), getDefaultRenderer, getCellRenderer, prepareRenderer | Choosing and adjusting renderers. |
TableColumn.setCellRenderer, setCellEditor, setHeaderRenderer, setHeaderValue | Per-column renderers, editors and headers. |
TableCellEditor.getTableCellEditorComponent(table, value, isSelected, row, column) | Supply the editor component. |
CellEditor.isCellEditable, shouldSelectCell, stopCellEditing, cancelCellEditing, getCellEditorValue, addCellEditorListener | Editing protocol. |
AbstractCellEditor, fireEditingStopped, fireEditingCanceled | Base class for editors. |
DefaultCellEditor(JTextField or JCheckBox or JComboBox), getComponent | Standard editors. |
JTable.setDefaultEditor, getDefaultEditor, editCellAt, isEditing, getCellEditor, getEditorComponent | Editing from the table. |
TableModel.isCellEditable, setValueAt | Model side of editing. |
UIManager.getBorder("Table.focusCellHighlightBorder"), client property terminateEditOnFocusLost | Look-and-feel border; commit on focus loss. |
Summary
- Renderers are rubber stamps: one component is configured and painted for each cell. Set every property on each call, keep the method fast, and use the returned component immediately.
- The column class selects a default renderer; register your own per class with
setDefaultRendereror per column withsetCellRenderer. OverrideprepareRendererfor table-wide effects. - Editing needs
isCellEditablein the model and an editor. Default editors handle text, numbers (with conversion and rejection) and booleans; install combo box editors per column. - Validate in
stopCellEditing(returnfalseto keep editing) and convert ingetCellEditorValue. Commit pending edits before saving. - Custom editors extend
AbstractCellEditorand implementgetTableCellEditorComponentandgetCellEditorValue; dialog-based editors callstopCellEditingorcancelCellEditingthemselves.
Practice Questions
1. A renderer sets a red foreground for overdue tasks, but after scrolling, some tasks that are not overdue also appear red. Why?
The renderer returns the same component for every cell. It sets the red foreground for overdue tasks but does not reset the color for the others, so a cell rendered after an overdue one keeps the red foreground. A renderer must set every property it changes on every call, for example setForeground(overdue ? Color.RED : table.getForeground()) (taking selection colors into account as well).
2. A renderer returns a JButton, and the program adds an action listener to it. Clicking the button in the table does nothing. Why?
A renderer's component is only used to paint the cell; it is not a child of the table and does not receive mouse events. The cell shows a picture of a button. To react to clicks, use a cell editor whose component is a button (it is live while the cell is being edited), or handle mouse events on the table and determine the cell with rowAtPoint and columnAtPoint.
3. A column holds Integer values and its class is reported as Integer. The user types "12a" into a cell. What happens?
The default numeric editor tries to convert the text with the Integer(String) constructor. The conversion fails, so stopCellEditing returns false: the editor stays open and its border turns red, and the model's setValueAt is not called. The user can correct the input or press Escape to cancel.
4. What is the difference between table.setDefaultRenderer(Color.class, r) and column.setCellRenderer(r)?
setDefaultRenderer associates the renderer with a value class: it is used for every column whose getColumnClass returns Color (and that has no renderer of its own). setCellRenderer installs the renderer on one specific TableColumn, regardless of the column's class, and takes precedence over the default renderer for that column.
5. A custom editor overrides stopCellEditing to hide a dialog but forgets to call super.stopCellEditing(). What goes wrong?
AbstractCellEditor.stopCellEditing fires the editingStopped event. Without it, the table never learns that editing ended: it does not call getCellEditorValue, the model is not updated, and the editor component stays installed over the cell. The override should hide the dialog and then return super.stopCellEditing().
Previous: Swing Tables: JTable, Table Models, Sorting and Filtering
Related reading
- Swing Tables: JTable, Table Models, Sorting and Filtering
- 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

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.