Semaphor Semaphor - 1 year ago 132
Java Question

Swing JTable with custom TableCellRenderer

In my java application I want to set the color and also the behavior when it is selected. For this I wrote a custom implementation of the TableCellRenderer and it is working as I want. But there is something I'm still confused about...

Here is the implementation of the


public class AccountMovementTableCellRenderer extends JLabel implements TableCellRenderer{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
//My implementation here...
return this;

And here the creation of the

AccountMovementTableCellRenderer accountMovementCellRenderer = new AccountMovementTableCellRenderer();
entryTable = new JTable(entryModel){
private static final long serialVersionUID = 1L;

public TableCellRenderer getCellRenderer(int row, int column){
return accountMovementCellRenderer;

I create only one instance of my CellRenderer but I was expecting one CellRenderer per cell and I was surprised it is working this way... The content and color is for every cell different but it uses always the same instance of the CellRenderer, so how could this work?

Answer Source

The Component that TableCellRenderer.prepareRenderer returns is reused to render the contents of the JTable - in your case your renderer extends JLabel (you can could have just extended DefaultTableCellRenderer) - this JLabel is used to paint the contents of the JTable. The prepareRenderer method is used to customize the JLabel for each cell before rendering. To quote Oracle's tutorial on the JTables

You might expect each cell in a table to be a component. However, for performance reasons, Swing tables are implemented differently.

Instead, a single cell renderer is generally used to draw all of the cells that contain the same type of data. You can think of the renderer as a configurable ink stamp that the table uses to stamp appropriately formatted data onto each cell. When the user starts to edit a cell's data, a cell editor takes over the cell, controlling the cell's editing behavior.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download