1

I have a JTable and i want a cell (or its row) painted in red when the value entered is higher than a certain value. I'm checking that into a TableModelListener to detect TableChange, so I see no way of colouring the table at the renderer (yet I'm sure it is possible, only it is unknown for me).

I also saw this question but i don't know how to use it.

Community
  • 1
  • 1
Roman Rdgz
  • 12,836
  • 41
  • 131
  • 207
  • no relation to the question you referenced - JTable is Swing, TableWhatever in the other is ... ? – kleopatra Jul 15 '11 at 15:26
  • 1
    yet not read snoracles swing tutorial? 1) you always need a renderer 2) you don't color the renderer, you color the rendering component: that's done by a custom renderer which configures the component's visual properties depending on context, f.i. on the value – kleopatra Jul 15 '11 at 15:31

2 Answers2

1

that job for prepareRendered as you can see here

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

Following is for single table cell you can extend it for row:

First take table column you want to pint and then add a TableCellRenderer to it as follows:

    TableColumnModel columnModel = myTable.getColumnModel();
    TableColumn column = columnModel.getColumn(5); // Give column index here
    column.setCellRenderer(new MyTableCellRenderer());

Make MyTableCellRendere class which implements TableCellRenderer and extends JLabel(so that we can give a background color to it). It will look something like following:

public class MyTableCellRenderer extends JLabel implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row,
            int col) {
        JLabel jLabel = (JLabel) value;
        setBackground(jLabel.getBackground());
        setForeground(UIConstants.black);
        setText(jLabel.getText());
        return this;
    }
}

Now in method where you are listening table cell value change do something like follow:

JLabel label = new JLabel(changedValue);
// check for some condition
label.setBackground(Color.red); // set color based on some condition
myTable.setValueAt(label, 0, 5); // here 0 is rowNumber and 5 is colIndex that should be same used to get tableColumn before.
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • could be, but that's not the point. Read the tutorial to learn how to do visual config correctly ;-) downvoted – kleopatra Jul 16 '11 at 08:04