开发者

Paint a single cell (or a single row) in a JTable without the renderer

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 th开发者_JAVA技巧e 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.


that job for prepareRendered as you can see here


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜