Coloring particular rows according to the first column values in JTable?
Asked Answered
U

1

2

I'm trying to color particular rows according to the first column values in JTable, but the code below colors the rows according to the row's index. My table has simply four columns. The first column has ID numbers. I need to color the rows according to these ID numbers. For example, if the first ID is 0 and the second is also 0, both of them should be "lightGray". Any idea, please?

table_1 = new JTable(){
    public Component prepareRenderer(TableCellRenderer renderer,int Index_row, int Index_col) {
        Component comp = super.prepareRenderer(renderer,Index_row, Index_col);
            //even index, selected or not selected
            if (Index_row % 2==0  &&  !isCellSelected(Index_row, Index_col)) {
                comp.setBackground(Color.lightGray);
            } else {
                comp.setBackground(Color.white);
            }
            return comp;
        }
    };

Here is how it looks now:

How it should look like

Unitive answered 28/12, 2012 at 21:6 Comment(1)
For readability, use common Java naming conventions; for safety, use the @Override annotation.Androclinium
A
6

Your renderer is choosing the color based on the row parameter passed to prepareRenderer(). The predicate row % 2 == 0 selects alternating rows for shading, as shown in your picture. Your question implies that you actually want to base shading on the value of column zero, ID. For this you need to examine the result of the getValueAt(row, 0).

The exact formulation depends on your model. Using this example, the following renderer shades rows starting with the letter "T".

private JTable table = new JTable(dataModel) {

    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
        Component comp = super.prepareRenderer(renderer, row, col);
        int modelRow = convertRowIndexToModel(row);
        if (((String) dataModel.getValueAt(modelRow, 0)).startsWith("T")
            && !isCellSelected(row, col)) {
            comp.setBackground(Color.lightGray);
        } else {
            comp.setBackground(Color.white);
        }
        return comp;
    }
};

image

Addendum: @mKorbel helpfully comments on the need to convert between model and view coordinates when sorting is enabled, as discussed here.

Androclinium answered 29/12, 2012 at 0:47 Comment(2)
+1 safer could be int modelRow = convertRowIndexToModel(row); for dataModel.getValueAtJesseniajessey
@mKorbel: Right you are! The converse would apply to SelectionAction. Thank you for critical review; updated.Androclinium

© 2022 - 2024 — McMap. All rights reserved.