java swing jtable外观属性一

public static void makeJTable(JTable table){
 

 //表格排序jdk1.6新功能
  TableRowSorter<TableModel>sorter = newTableRowSorter<TableModel>(table.getModel());
  table.setRowSorter(sorter);
  
  //设置行高
  table.setRowHeight(Constants.TB_ROW_HEIGHT);
  
  //设置表格线
  table.setGridColor(SystemColor.controlHighlight);
  
  //table.getTableHeader().set
  //表头居中显示
  JTableHeader tbh =table.getTableHeader();
  DefaultTableCellRenderer renderer =(DefaultTableCellRenderer)tbh.getDefaultRenderer();
  renderer.setHorizontalAlignment(SwingConstants.CENTER); 
  
  //设置表头字体
  //Font headFont =UIManager.getFont("Menu.font");
  //tbh.setFont(headFont);
  
  //table.setFont(UIManager.getFont("Menu.font"));

  try {
   DefaultTableCellRenderertcr = new DefaultTableCellRenderer() {
    
    privatestatic final long serialVersionUID = 1826425922704465800L;

    publicComponent getTableCellRendererComponent(JTable table,
      Objectvalue, boolean isSelected, boolean hasFocus,
      introw, int column) {
     
     //设置奇偶行颜色
     if(row % 2 == 0){
      setBackground(Color.white);// 设置奇数行底色
     }
     elseif (row % 2 == 1){
      setBackground(newColor(237, 237, 237)); // 设置偶数行底色
     }
     
     //如果为数值则右对齐
     Patternp = Pattern.compile("^(-?\d+)(\.\d+)?$");
     Stringsv = (value != null ? value.toString() :"");  
     if(p.matcher(sv).matches()){
      this.setHorizontalAlignment(SwingConstants.RIGHT);
      
      //自动格式化小数位
      if(sv.indexOf(".")!= -1){
       value= StringTools.formatMoney(Double.parseDouble(sv));
       //System.out.println(sv+ ", d:" + Double.parseDouble(sv) + ",f:" + value);
      }
      
     }else{
      this.setHorizontalAlignment(SwingConstants.LEFT);
     } 
     
     returnsuper.getTableCellRendererComponent(table, value, isSelected,hasFocus, row, column);
    }
   };
   
   for (int i =0; i < table.getColumnCount(); i++) {
    TableColumntc = table.getColumn(table.getColumnName(i));
    tc.setCellRenderer(tcr);
    
   }
  } catch (Exception ex) {
   ex.printStackTrace();
  }
  
  //设置table外层scrollPane的背景色
  Container c =table.getParent();
  if(c instanceofJViewport){
   JViewport jp= (JViewport)c;
   jp.setBackground(newColor(250, 250, 250));
  }
 }


你可能感兴趣的:(java swing jtable外观属性一)