We help IT Professionals succeed at work.

TableCellRenderer - Set font color

dshrenik asked
Please let me know how I can set the font color. Thanks!
Watch Question

Awarded 2011
Awarded 2011
setForeground(Color) in CellRenderer, see below:

Basically you need to install a custom cell renderer. You can easily create a custom cell renderer as follows. (You define SPECIAL_ROW and SPECIAL_COLUMN)

import javax.swing.table.*;
import javax.swing.*;
import java.awt.*;

public class YourTableCellRenderer
       extends DefaultTableCellRenderer {
  public Component getTableCellRendererComponent(JTable table,
                                                 Object value,
                                                 boolean isSelected,
                                                 boolean hasFocus,
                                                 int row,
                                                 int column) {
    Component c = 
      super.getTableCellRendererComponent(table, value,
                                          isSelected, hasFocus,
                                          row, column);

    // Only for specific cell
    if (row == SPECIAL_ROW && column == SPECIAL_COULMN) {
       c.setFont(/* special font*/);
       // you may want to address isSelected here too
       c.setForeground(/*special foreground color*/);
       c.setBackground(/*special background color*/);
    return c;

To install the cell renderer use various methods from JTable

table.setDefaultRenderer(new YourTableCellRenderer());

or TableColumn class e.g.

TableColumn.setCellRenderer(new YourTableCellRenderer());

Open in new window

Awarded 2011
Awarded 2011

It is basically the same as changing sell color - but instead of setBackground you make setForeground