使用CellRenderer从jTable中选择specefic单元格

时间:2013-09-24 13:17:59

标签: java swing jtable

我想从jtable

同时为特定单元格着色

例如,column = 1row i+2(i从0到5)的单元格。

我使用CustomTableCellRenderer成功地为特定单元格着色,如示例show

public class CustomTableCellRenderer extends DefaultTableCellRenderer 
{  
   int x;
   int y;

    CustomTableCellRenderer(int x,int y){ //constructor

        this.x= x;
        this.y=y;
    }   

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus, int row, int column) 
    {
        Component cell = super.getTableCellRendererComponent
           (table, value, isSelected, hasFocus, row, column);

        if ( ((row == x) && (column == y))) { //test of equivalence of x and y as parameter
                cell.setBackground(Color.green);
            }

            else {
                cell.setBackground(Color.WHITE);
            }
        return cell;
    }
}

1 个答案:

答案 0 :(得分:0)

Try this

table.setDefaultRenderer(Object.class, new TableCellRenderer(){
            private DefaultTableCellRenderer DEFAULT_RENDERER =  new DefaultTableCellRenderer();
            private Component comp;

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if(isSelected){

                    c.setBackground(Color.YELLOW);
                }else{
                if (row%2 == 0){
                    c.setBackground(Color.WHITE);

                }
                else {
                    c.setBackground(Color.LIGHT_GRAY);
                }     }

                return c;
            }

        });