0

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!

user3921232
  • 597
  • 2
  • 6
  • 14

1 Answers1

1

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;
};
DavidPostill
  • 7,734
  • 9
  • 41
  • 60