如何更改所选单元格的背景?

时间:2013-05-25 16:36:42

标签: java swing jtable tablecellrenderer

如何在jTable中更改所选单元格的背景文件?

我已经编写了表格渲染,但它分配了所有行,并且看不到现在选择的单元格类型。

public class MyTableRanderer extends DefaultTableCellHeaderRenderer{

    @Override
    public Component getTableCellRendererComponent(JTable jtable, Object obj,
            boolean isSelected, boolean hasFocus, int row, int col) {
        setText(obj.toString());

        if(isSelected){
            setBackground(Color.ORANGE);
            setForeground(Color.BLACK);
        } else {
            setBackground(Color.WHITE);
            setForeground(Color.BLACK);
        }

        return this;
    }

}

编辑:

public class MyTableRanderer extends DefaultTableCellHeaderRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable jtable, Object obj,
            boolean isSelected, boolean hasFocus, int row, int col) {
        setText(obj.toString());

        Component cell = super.getTableCellRendererComponent(
                jtable, obj, isSelected, hasFocus, row, col);


        if (isSelected) {
            setBackground(Color.ORANGE);
            cell.setBackground(Color.green);
            setForeground(Color.BLACK);
        } else {
            setBackground(Color.WHITE);
            setForeground(Color.BLACK);
        }

        return this;
    }
}

2 个答案:

答案 0 :(得分:1)

尝试在getTableCellRendererComponent函数中插入此内容,以定位特定单元格:

Component cell = super.getTableCellRendererComponent(
   table, obj, isSelected, hasFocus, row, column);
if (isSelected) {
   cell.setBackground(Color.green);
} 

答案 1 :(得分:1)

  

如何在jTable中更改所选单元格的背景文件?

     

我已经编写了表格渲染,但它分配了所有行,并且   看不到现在选择什么样的细胞

然后

需要测试两种方法if (isSelected & hasFocus) {