Search code examples
javaswingjtabletablecellrenderer

JTable - extend default CellRenderer


I use a big JTable and I want to extend the CellRenderer for every Class, so every second Row has a gray Background, to make it more readable.

This gray Background for every second row should look something like this: http://i61.tinypic.com/of3sky.png

But I still want the default alignment for every Class and the default settings for isSelected and hasFocus.

The code for the Background should be simple, something like:

if(row % 2 == 0){
            super.setBackground(new Color(200, 200, 200));
        }
        else{
            super.setBackground(Color.WHITE);
        }

But how to get the default CellRenderer for every Class, and extend it in this way?

Thank you in advance!


Solution

  • From JTable Alternate Row Background

    To make a JTable render each row in a different color, you just have to extend the JTable's prepareRender method.

    JTable table = new JTable(){
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column){
            Component returnComp = super.prepareRenderer(renderer, row, column);
            Color alternateColor = new Color(252,242,206);
            Color whiteColor = Color.WHITE;
            if (!returnComp.getBackground().equals(getSelectionBackground())){
                Color bg = (row % 2 == 0 ? alternateColor : whiteColor);
                returnComp .setBackground(bg);
                bg = null;
            }
            return returnComp;
    };