JTable表格設定隔行顏色
阿新 • • 發佈:2018-11-11
- 定義函式,隔行設定表格背景色
- 在表格顯示之前呼叫,
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();
}
}