Skip to content
Advertisement

Change Color of JTable Row Based on the Value of the Database

tblApplicant = new javax.swing.JTable(){
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
    {
    Component c = super.prepareRenderer(renderer, row, column);

    //  Alternate row color
    String value = (String) tblApplicant.getValueAt(row, 4);
    if (value == "Single" && !isRowSelected(row))
    c.setBackground(Color.LIGHT_GRAY);

    return c;
}

};

This is my New Codes im trying to get the value of column 4 and equal it to single if its true the background is change. but this is not working

Advertisement

Answer

Overriding the prepareRender(...) method of the JTable allows your to customize rendering for the entire row based on a value in one of the columns.

The basic logic would be something like:

public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
    Component c = super.prepareRenderer(renderer, row, column);

    //  Color row based on a cell value

    if (!isRowSelected(row))
    {
        c.setBackground(getBackground()); // set default background

        int modelRow = convertRowIndexToModel(row);
        String value = (String)getModel().getValueAt(modelRow, ???);

        if ("Single".equals(value)) c.setBackground(Color.GREEN);
    }

    return c;
}

Check out Table Row Rendering for more information and working examples.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement