Customize single cells in JTable

Categories Java, Languages

JTables are very useful for develop desktop applications but when it comes to customize properties at cell level it can be a little tricky. The key concept here is that we have to deal with Cell Renderers for each column. TableCellRenderer is an interface that forces to implement the following method:

Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)

The most common way to customize Cell Rendering is to create a class that extends a Component and implements TableCellRenderer. Most people use a simple JLabel. For example,  the following class will allow us to change the background of a single cell:

public class JLabelCellRenderer extends JLabel implements TableCellRenderer
  public Component getTableCellRendererComponent(JTable table,Object value,
  boolean isSelected,boolean hasFocus, int row,int col)
    JLabel label = (JLabel) value;
    setOpaque(true); /* Important to see the background color */
    return this;

Now lets create our table and use our custom cell renderer:

JTable table = new JTable();
String[] columnNames = {"Red","Blue"}; /* Two columns */
JLabel[][] data = new JLabel[1][2]; /* One row, two columns */
data[0][0] = new JLabel("");
data[0][1] = new JLabel("");
table.setModel(new DefaultTableModel(data, columnNames));
/* Now we use our new class for rendering cells */
table.getColumnModel().getColumn(0).setCellRenderer(new JLabelCellRenderer());
table.getColumnModel().getColumn(1).setCellRenderer(new JLabelCellRenderer());

Now we put it in a JFrame and the result is the following:

JTable 2 cell colors example
So it worked! Now you can improve the cell renderer and get more properties from the JLabel such as Font, Foreground, Border… etc.
I’ve developed a more complex but funnier example in which I’ve used most common methods and properties to customize the aspect of a JTable. A couple of screenshots are shown below so you can get the idea.

JTable example serious JTable example smiling


You can get the source code -> (363 downloads)

and the executable jar file ->  Smiley.jar (275 downloads)


No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.