设置一个JTable中某些单元格的背景色

Object [][] data={
    {null, null, null, null,null,null,1},
    {2, 3, 4, 5, 6, 7, 8},
    {9, 10, 11, 12, 13, 14, 15},
    {16, 17, 18, 19, 20, 21, 22},
    {23, 24, 25, 26, 27, 28, 29},
    {30, 31, null, null, null, null,null}
  };
  String [] head={
    "日", "一", "二", "三","四","五","六"
  };
  JTable jTable1=new JTable(data,head);
  jTable1.setRowHeight(40);
  jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
  JScrollPane jScrollPane1=new JScrollPane();
jTable1.setCellSelectionEnabled(true);
  jTable1.setFont(new Font("SimSun", 0, 20));
  jTable1.getTableHeader().setFont(new Font("SimSun",0, 20));
  jTable1.getTableHeader().setReorderingAllowed(false);
  jTable1.getTableHeader().setResizingAllowed(false); 
  jTable1.setEnabled(false);
  TableColumn column=null;
  for(int i=0;i<7;i++){
   column=jTable1.getColumnModel().getColumn(i);
   column.setPreferredWidth(60);
  }
  DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() { 
   public Component getTableCellRendererComponent(JTable table, 
     Object value, boolean isSelected, boolean hasFocus, 
     int row, int column) { 
    if((column == 0&&row!=3)||column == 6||(column == 3&&row==3)) 
     setBackground(new java.awt.Color(255, 255, 0)); 
    else 
     setBackground(new Color(255,255,255)); 
    return super.getTableCellRendererComponent(table, value, 
      isSelected, hasFocus, row, column); 
   } 
  }; 
  for(int i=0;i<7;i++){
   jTable1.getColumn(head[i]).setCellRenderer(tcr); 
  }
  jScrollPane1.setViewportView(jTable1);

你可能感兴趣的:(设置一个JTable中某些单元格的背景色)