-1

I use TableCellRenderer in a function to change the color of a row.

public void change_color(JTable tableName){ 
 tableName.setDefaultRenderer(Object.class, new TableCellRenderer(){
    private DefaultTableCellRenderer DEFAULT_RENDERER =  new DefaultTableCellRenderer();

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

                    c.setBackground(Color.RED);


       //Add below code here
                return c;
            }

        });

 }   

It changes the color of entire table. To call this function i use following condition.

if(ellapsed.getMinutes() > 30)
            {
           change_color(table_dineIn,ellapsed.getMinutes());
            }

Cant figure out the problem. I have tried other codes to but nothing helped me.

BackSlash
  • 21,927
  • 22
  • 96
  • 136
  • A simple Ctrl+click on the method you're invoking shows the problem. When you set the background for the `DEFAULT_RENDERER` you set it as the default for others as well. Yay. Also, notice that you don't have ANY logic to differentiate rows. The code snippet at the bottom of the question does not seem to have any connection with the renderer. Why in the world were you expecting it to do that? What's wrong with the methods that Google gives you on "jtable color single row"? That includes quite a few SO questions as well. – Ordous Oct 02 '14 at 14:25
  • That is what i actually wanted to ask... how to differentiate the rows – Shoaib Bazmi Oct 02 '14 at 14:30
  • possible duplicate of [Changing Cell Color without changing color in other cells (Jtable)](http://stackoverflow.com/questions/24555289/changing-cell-color-without-changing-color-in-other-cells-jtable) – Marco13 Oct 02 '14 at 15:47

2 Answers2

0

The cell renderers in JTable, JList etc. are used like a stamp (see Editors and Renderers for details).

This means that usually, the same (identical) JComponent is used for painting all the cells. This component is only filled with the appropriate contents before it is used for painting the cell. And when the background is set to RED, it will remain red until it is set to a different color.

I'm not sure what you wanted to achieve by using this DEFAULT_RENDERER instance. You could simply inherit from DefaultTableCellRenderer and return the component (which is in fact the renderer itself) direcly. However, in any case, you'll have to include some code that makes sure that the appropriate color is set for every call, roughly like

....
if (shouldBeRed(row, column)) {
    c.setBackground(Color.RED);
} else {
    c.setBackground(notRed);
}
return c;

(note that this can actually be hidden in the call to the super method if you extend DefaultTableCellRenderer, but the details here depend on whether you'll keep this DEFAULT_RENDERER instance or not...)

You might also be interested in this example of blinking table cells, showing how several table cells may be assigned different colors based on certain criteria.


EDIT: An example. Although I usually try to avoid answereing questions like this with examples like this, because even for the slightest modification, you'll ask another question, which in this case will probably in the line of

  • how to un-highlight the row
  • how to highlight multiple rows
  • how to highlight multiple rows with different colors
  • ...

You'll find answers to all these questions in https://stackoverflow.com/a/24556135/3182664 - in the meantime, I'll mark this question as a duplicate.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;

public class TableRowColor 
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("TableRowColor");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().setLayout(new BorderLayout());

        final JTable table = createTable();
        JScrollPane scrollPane = new JScrollPane(table);
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

        JButton changeColorButton = new JButton("Change color");
        changeColorButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                changeColor(table, 1);
            }
        });
        frame.getContentPane().add(changeColorButton, BorderLayout.SOUTH);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static JTable createTable()
    {
        String[] columnNames = { "First Name", "Last Name", "Sport", };
        Object[][] data = { { "Kathy", "Smith", "Snowboarding" },
            { "John", "Doe", "Rowing" }, { "Sue", "Black", "Knitting" },
            { "Jane", "White", "Speed reading" }, { "Joe", "Brown", "Pool" } };
        return new JTable(data, columnNames);
    }

    public static void changeColor(JTable table, final int coloredRow)
    {
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
        {
            @Override
            public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row,
                int column)
            {
                super.getTableCellRendererComponent(table, value, isSelected,
                    hasFocus, row, column);
                if (row == coloredRow)
                {
                    setBackground(Color.RED);
                }
                else
                {
                    setBackground(null);
                }
                return this;
            }
        });
        table.repaint();

    }

}
Community
  • 1
  • 1
Marco13
  • 53,703
  • 9
  • 80
  • 159
-2

The following would color 30th row of the table:

public void change_color(JTable tableName){ 
 tableName.setDefaultRenderer(Object.class, new TableCellRenderer(){
    private DefaultTableCellRenderer DEFAULT_RENDERER =  new DefaultTableCellRenderer();

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
               if (row == 30) {
                   c.setBackground(Color.RED);
                }      
                return c;
            }

        });

 }   

Edit:

If you want to choose table color based on data, add that data to the the table model (e.g. a Time stored in particular column), then use the model in the renderer. For example:

static final int TIME_ELLAPSED_COL = ...;
...
if (((Time) table.getModel().getValueAt(row, TIME_ELLAPSED_COL)).getMinutes() > 30) {
   c.setBackground(Color.RED);
}
...
david a.
  • 5,283
  • 22
  • 24
  • On the basis of ellapsed.getHours()... I am adding the row and if ellapsed.getMinutes() > 30 i want that row background to be red – Shoaib Bazmi Oct 02 '14 at 13:30
  • while(rs.next()) { dtm.addRow(new Object[]{rs.getString("Order Number"),rs.getString("Table"),rs.getString("Waiter Name"),rs.getString("Time elapsed"), false}); Time ellapsed = rs.getTime("Time elapsed"); if(ellapsed.getMinutes() > 30) { change_color(table_dineIn); } – Shoaib Bazmi Oct 02 '14 at 13:31
  • Your answer is not working too its still coloring the whole table – Shoaib Bazmi Oct 02 '14 at 13:34
  • ITS STILL COLORING THE WHILE TABLE – Shoaib Bazmi Oct 02 '14 at 14:19