1

I would like to know how do i change the background color of a cell in a Table without any response from users. For example, if there is a change in one of my variables due to some unrelated method calls, which I would like for to be reflected in my table. Example, a method changes a value of my array that I used to initialize my table, however the user had no hand in it, like say a elapsed time change in value. So how do I reflect it on my table, or is there any way I could manually call the TableCellRenderer

EDIT: updated question with code snippets here

Yash Mathur
  • 243
  • 2
  • 7
  • 3
    Use a [table cell renderer](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#renderer) (dynamically). – Andrew Thompson May 09 '20 at 21:34
  • 2
    If you had provided a [mre] that didn't change the cell color, then @AndrewThompson could have answered with a corrected example. – Gilbert Le Blanc May 09 '20 at 21:42
  • 1
    You never call the TableCellRenderer directly. You update the data in the TableModel and the model will tell the table to repaint itself. – camickr May 09 '20 at 23:01

1 Answers1

1

As advised use a custom cell renderer:

import java.awt.Color;
import java.awt.Component;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;

public class CellRenderDemo {

    private static final int MAX =120;
    private static Object[] columnName = {"Item", "Value"};
    private static Object[][] data = {{"Value A", 12}, {"Value B", 34},  {"Value C", 66}};
    private final JTable table;

    CellRenderDemo() {
        table = new JTable(data, columnName);
        table.getColumnModel().getColumn(1).setCellRenderer(new CustomRenderer());//use custom cell rendered for col 1
    }

    void randomizeData(){
        Random rnd = new Random();
        TableModel model = table.getModel();
        new Timer(1000, e->{
            model.setValueAt(rnd.nextInt(MAX+1), rnd.nextInt(model.getRowCount()), 1);
        }).start();
    }

    JTable getTable() {
        return table;
    }

    static class CustomRenderer extends DefaultTableCellRenderer {

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

            int cellValue = (int)value;
            if(cellValue <= MAX / 3){ //change color based on value 
                cellComponent.setBackground(Color.PINK);
            } else if ( cellValue > 2*MAX / 3){
                cellComponent.setBackground(Color.CYAN);
            } else {
                cellComponent.setBackground(Color.YELLOW);
            }
            return cellComponent;
        }
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            JFrame frame = new JFrame();
            CellRenderDemo cd = new CellRenderDemo();
            frame.add(new JScrollPane(cd.getTable()));
            frame.pack();
            cd.randomizeData();
            frame.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

enter image description here

c0der
  • 18,467
  • 6
  • 33
  • 65
  • Okay, thanks a lot. I had just assumed that the cell renderer would only call if there is a user defined change in the viewport. sorry for the silly question. – Yash Mathur May 10 '20 at 19:50
  • I am glad I could help. – c0der May 11 '20 at 03:43
  • Hey i just tried using my custom cell renderer, and I have an array which changes values when user clicks a button. So, I want some changes to be reflected in my tables when that happens, however it happens only sometimes, other times it is only reflected when I click on the table. any suggestions? – Yash Mathur May 11 '20 at 18:44
  • I have done the same. here is the link to the post [link](https://stackoverflow.com/questions/61764022/updating-calling-jtable-rendering-when-a-value-is-changed-manually-dynamically) – Yash Mathur May 13 '20 at 10:50