How to change the color of a JTable entire row having a particular column value

前端 未结 3 1268
时光取名叫无心
时光取名叫无心 2020-12-21 11:18

I have a Jtable which gets populated from an array of values. My code is like this:

  private static final String[] columnNames = {\"Line Number\", \"Error\"         


        
3条回答
  •  囚心锁ツ
    2020-12-21 11:59

    You can create a custom cell renderer. In its implementation, check if percentage value is > 30 for a given row, then highlight this cell.

    For example:

    class SomeRenderer extends DefaultTableCellRenderer {
        public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row,
                int column) {
    
            Component c = super.getTableCellRendererComponent(table,
                    value, isSelected, hasFocus, row, column);
    
            if (isHighlightingEnabled){
                Integer percentage = (Integer) table.getValueAt(row, 3);
                if (percentage > 30)
                    c.setBackground(Color.RED);
            }
            return c;
        }
    }
    

    You may enable/disable this rendering logic upon action if needed.

    See Using Custom Renderers for more details.

提交回复
热议问题