swing JTable 行颜色设置

发布时间:2022-10-30 00:18:23

在编写代码生成器时,有很多表格,为了在显示时行记录更加直观,所以需要对表格中行的背景色切换, 这样在操作表格时体验更好。

设置背景色时是根据表中的记录的index来判断的,所以需要先设置数据,即setModel后再设置颜色

@SuppressWarnings("serial")
	public static void setColor(JTable table) {
		try {
			
			DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer() {
				// 重写getTableCellRendererComponent 方法
				@Override
				public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
						boolean hasFocus, int row, int column) {
					Color backgroundColor = null;
					if (row % 2 == 0) { // 偶数
						backgroundColor = new Color(245, 245, 245);//偶数行的背影色
					} else {
						backgroundColor = Color.white;
					}
					setBackground(backgroundColor);
					Color fontColor = new Color(51, 51, 51);
					setForeground(fontColor);
					return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
				}
			};
			// 对每行的每一个单元格
			int columnCount = table.getColumnCount();
			for (int i = 0; i < columnCount; i++) {
				table.getColumn(table.getColumnName(i)).setCellRenderer(dtcr);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Card image cap
APP STORE
Card image cap
应用宝
Card image cap
小米
Card image cap
华为