Joeyos's Blog Software Engineer

JTable表格设置隔行颜色

2019-01-17
Quan Zhang

  1. 定义函数,隔行设置表格背景色
  2. 在表格显示之前调用,setColumnColor(table);,table是你新建的表格。
public static void setColumnColor(JTable table) {
	try
	{
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer(){
			private static final long serialVersionUID = 1L;
			public Component getTableCellRendererComponent(JTable table,Object value, boolean isSelected, boolean hasFocus,int row, int column){
				if(row%2 == 0)
					setBackground(Color.WHITE);//设置奇数行底色
				else if(row%2 == 1)
					setBackground(new Color(220,230,241));//设置偶数行底色
				return super.getTableCellRendererComponent(table, value,isSelected, hasFocus, row, column);
			}
		};
		for(int i = 0; i < table.getColumnCount(); i++) {
			table.getColumn(table.getColumnName(i)).setCellRenderer(tcr);
		}
		tcr.setHorizontalAlignment(JLabel.CENTER);
	}
	catch (Exception e){
		e.printStackTrace();
	}
}

Similar Posts

Comments