setSelectionBackGround()没有在jTable中设置颜色

时间:2014-12-03 09:58:16

标签: java swing jtable tablecellrenderer

我认为prepareRenderer(...)造成了麻烦。我的jTable创建代码是: -

jTable1 = new javax.swing.JTable(){
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
    Component c = super.prepareRenderer(renderer, row, column);
    if(column==0){
        c.setBackground(new java.awt.Color(223, 223, 223));
        c.setForeground(new Color(121, 63, 63));
        c.setFont(new java.awt.Font("Tahoma", java.awt.Font.BOLD, 12));
    }else{
        c.setBackground(new java.awt.Color(235, 235, 235));
        c.setFont(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 12));

    }
    return c;
}
};

现在,当我使用: -

    jTable1.setSelectionBackground(Color.BLACK);

它不起作用。知道怎么解决吗?

编辑:我在完全删除prepareRenderer(...)方法后测试了该程序,我可以进行黑色选择

2 个答案:

答案 0 :(得分:1)

这是DefaultTableCellRenderer的代码片段

    if (isSelected) {
        super.setForeground(fg == null ? table.getSelectionForeground()
                                       : fg);
        super.setBackground(bg == null ? table.getSelectionBackground()
                                       : bg);
    }

如您所见,选择背景设置为渲染器(实际上在您的调用中为super.prepareRenderer(渲染器,行,列))

之后,您只需将背景重置为其中一种颜色,具体取决于列。但无论哪个列号都可以替代选择背景。

如果列!= 0调用

c.setBackground(getSelectionBackground());

答案 1 :(得分:0)

终于找到了解决方案......

public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
if(column==0){
    c.setBackground(new java.awt.Color(223, 223, 223));
    c.setForeground(new Color(121, 63, 63));
    c.setFont(new java.awt.Font("Tahoma", java.awt.Font.BOLD, 12));
}else{
    setBackground(new java.awt.Color(235, 235, 235));//c.setBackground(..) was the problem
    c.setFont(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 12));

}
return c;
}