Search code examples
javaswingjtablerenderer

JTable coloring specific gridline in Java


I have this 8x8 table and and I want to color the grid of the first and the second cell at the very top of the table with red. My question is it possible to do this?


Solution

  • EDIT: I deleted this because I thought this wasn't what OP wanted. I'm undeleting it at OP's request.

    I have this 8x8 table and and i want to color the grid of the first and the second cell at the very top of the table with red. My question is it possible to do this?

    Yes of course.

    One way to do it would be to extend an existing renderer and override the getTableCellRendererComponent method.

    For example:

    public class GridlineCellRenderer extends DefaultTableCellRenderer {
    
        @Override
        public Component getTableCellRendererComponent (
            JTable table,
            Object value,
            boolean isSelected,
            boolean hasFocus,
            int row,
            int column
        ) {
            final Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if ( row == 0 && (column == 0 || column ==1 ) {
                cell.setBackground( Color.RED );
            }
            return cell;
        }
    }
    

    You then need to warn your JTable that you want to use this renderer for certain types of data.

    For example if you want to use this for cells containing Integer, the following should work:

    JTable myJTable = ...
    myJTable.setDefaultRenderer(Integer.class, new GridlineCellRenderer() );