user237462
user237462

Reputation: 421

Java JTable - Coloring the Selected Row

Ive searched through but cant seem to find an answer thats similar.

Id like to color a selected row AND at the same time permanently color other rows. i.e have the total Column always GRAY but dynamically make the selected row GRAY

Im trying

JTable table = new JTable(model) {
        public Component prepareRenderer(TableCellRenderer renderer, int index_row, int index_col) {
            Component comp = super.prepareRenderer(renderer, index_row, index_col);
            //odd col index, selected or not selected
            if(isCellSelected(index_row, index_col)){
               comp.setBackground(Color.GRAY);  
            }
            if (index_col == 34) {
                comp.setBackground(Color.GRAY);                   
            } else {
                comp.setBackground(Color.WHITE);
                setSelectionForeground(Color.BLUE);

                setSelectionBackground(Color.GRAY); // Thought this would work but has no affect.
                // comp.setFont(new Font("Serif", Font.BOLD, 12));

            }
            return comp;
        }
    };

But its not changing the background Color on selected Row, Just the Total Row.

Upvotes: 0

Views: 1255

Answers (1)

DirkNM
DirkNM

Reputation: 2664

I'm not sure, but I think you need an "else" after the if (isCellSelected(index_row, index_col)) block. This could solve your problem:

...
if (isCellSelected(index_row, index_col)){
    comp.setBackground(Color.GRAY);  
} else {
    if (index_col == 34) {
        comp.setBackground(Color.GRAY);                   
    } else {
        comp.setBackground(Color.WHITE);
    }
}
...

Upvotes: 1

Related Questions