views:

159

answers:

2

Suppose you have a JTable and for each cell you want to display three strings with different color, say value1 (red), value2 (blue), value3 (green).

I overrode the getTableCellRendererComponent of DefaultTableCellRenderer but setForeground(Color) method gives an unique color for all the string showed in the cell.

@Override
public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {
    String s = table.getModel().getValueAt(row,column).toString();

    StringTokenizer st = new StringTokenizer(s," ");
    int nToken=st.countTokens();

    value1=st.nextToken();
    value2=st.nextToken();
    value3=st.nextToken();
    // so now all the values are blue...
    setForeground(Color.blue);

    return super.getTableCellRendererComponent(table, value, isSelected,
            hasFocus, row, column);

}
+1  A: 

The default renderer for a cell table is a JLabel. This component supports HTML tags. The easiest solution you can have is to use HTML to render the Strings with different colours. So you can build a String such as:

 <html><font color="blue">A String</font><font color="red">Another String</font></html>

And set it to the cell, and you don't have to worry about the renderer.

Most swing components allow you to use HTML, this is not only limited to tables.

Another possibility is that you create a class that extends from JComponent, and program paintComponent() so it draws these three strings in different colors. Then you can set this component as the renderer. But this is way more complicated. Because the renderer works like a "stamp", it will stamp the right colors when the cells are drawn. This is useful if your needs are to, for example, draw extremely complex and custom graphics on a cell.

I would stick with using HTML if you don't have a humongous amount of cells.

Mario Ortegón
HTML components in tables gets very slow very quickly. You can cache the components, but that gets tricky in anything other than some special cases.
Tom Hawtin - tackline
The alternative, though, writing your own JComponent, is fast. But tricky to get it right
Mario Ortegón
+2  A: 
Andrew