JTable CustomRenderer Issue
Asked Answered
R

1

1

I have created one Jtable.This table consist of two columns name and timestamp. I want to make color of row yellow if name is "jane". Following is the code for that :-

    class CustomRenderer 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);
        String name = table.getModel().getValueAt(row, 0).toString();

        if (name.trim().equals("jane")) {
            c.setBackground(Color.YELLOW);
        }
        return c;
    }
}

However instead of changing color of row to yellow for particular name, it is changing color of every row.I am setting data of table as following

tableModelName = (DefaultTableModel)jTableName.getModel();

jTableName.setDefaultRenderer(Object.class,new CustomRenderer());

for(int i=0; i<records.size(); i++)
         {
            tableModelName.addRow(records.get(i));          

         }

What I am doing wrong ?

Related answered 29/11, 2012 at 17:40 Comment(1)
Make sure to use table.convertRowIndexToModel() and table.convertColumnIndexToModel() before accessing the model. Else, any table sorting or column reordering will make your code fail.Bolide
G
4

You need an else clause to set the background color to something besides yellow if the name is not "jane". A single renderer instance is used for all rendering, so once you set the color to yellow on that instance, it stays yellow.

Take a look at the JTable source code to see how the built-in renderers work:

    if (isSelected) {
        setForeground(table.getSelectionForeground());
        super.setBackground(table.getSelectionBackground());
    }
    else {
        setForeground(table.getForeground());
        setBackground(table.getBackground());
    }

For an easier way of doing this, you might try subclassing JTable and overriding prepareRenderer. This is handy for changes that affect entire rows like this, so you can use custom renderers for the individual cells, and tweak all renderers for a row in the prepareRenderer method.

Gimel answered 29/11, 2012 at 17:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.