JTable Set Cell color by specific value

I am trying to write a method that for the given parameters (value, color) sets the color against the background of a cell whose value is equal to cellValue.

What my method actually does is it sets the background color of the cells for the whole row and when I select the row in the table and I want the method to set only the color in a specific column (where cellValue is equal to the value) every time I call the method .

void setCellBackgroundColor(boolean cellValue, final Color color) { List<List<Object>> data = tView.getTTableModel().getData(); for (int row = 0; row < data.size(); row++) { for (int col = 0; col < data.get(row).size(); col++) { TableCellRenderer renderer = tView.table.getCellRenderer(row, Col); Component component = tView.table.prepareRenderer(renderer, row, col); boolean bValue = TDataTypeRenderer.parseIntoRealValue( data.get(row).get(col) ) ); if (bValue == cellValue) { component.setBackground(color); } } 
+7
java swing jtable tablecellrenderer
source share
1 answer

when I select a row in a table and want the method to set only the color in a specific column

Try using the overridden prepareRenderer() method suggested by @mKorbel.

code example:

 Object[] columnNames = { "A", "B", "C", "D" }; Object[][] data = { { "abc", new Double(850.503), 53, true }, { "lmn", new Double(36.23254), 6, false }, { "pqr", new Double(8.3), 7, false }, { "xyz", new Double(246.0943), 23, true } }; JTable table = new JTable(data, columnNames) { @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int col) { Component comp = super.prepareRenderer(renderer, row, col); Object value = getModel().getValueAt(row, col); if (getSelectedRow() == row) { if (value.equals(false)) { comp.setBackground(Color.red); } else if (value.equals(true)) { comp.setBackground(Color.green); } else { comp.setBackground(Color.white); } } else { comp.setBackground(Color.white); } return comp; } }; 

When selecting the first row:

enter image description here

When selecting the second row.

enter image description here

More details


EDIT

According to your last comment

Is it possible to change the color by cutting (selecting) a row in a table?

Yes, just remove the check for the selected row.

  Object value = getModel().getValueAt(row, col); if (value.equals(false)) { comp.setBackground(Color.red); } else if (value.equals(true)) { comp.setBackground(Color.green); } else { comp.setBackground(Color.white); } 

enter image description here

+9
source share

All Articles