Java JTable - 为所选行着色

时间:2014-10-02 10:14:50

标签: java colors jtable

我已经搜索过,但似乎无法找到类似的答案。

我想为选定的行着色,同时永久地为其他行着色。 即总列总是灰色但动态地使所选行为灰色

我正在尝试

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;
        }
    };

但它没有改变所选行的背景颜色,只是总行。

1 个答案:

答案 0 :(得分:1)

我不确定,但我认为你需要if (isCellSelected(index_row, index_col))之后的“其他”  块。这可以解决您的问题:

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