Search code examples
javajtablecellbackground-color

Change only one cell's color in JTable


I know I can set the whole column's background color with this code, but how can I set a different color for each cell? I have a table with two columns and one to one thousand rows.

words.getColumn("columnNameHere").setCellRenderer(
    new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            setText(value.toString());
            setBackground(Color.RED);
            return this;
        }
    }
);

Solution

  • The row and column number are passed into getTableCellRendererComponent. So you could do something like:

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        setText(value.toString());
        if (row==12 && column==2) {
            setBackground(Color.RED);
        }
        return this;
    }