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

前端 未结 1 941
Happy的楠姐
Happy的楠姐 2020-12-12 00:49

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

1条回答
  •  伪装坚强ぢ
    2020-12-12 01:20

    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.

    0 讨论(0)
提交回复
热议问题