代码片断如下:
@Override public void mouseClicked(MouseEvent e) { // 左键单击事件 if (e.getClickCount() == 1) { System.out.println("listener out "); JTable table = (JTable) e.getSource(); Point p = new Point(e.getX(), e.getY()); // 当前选中单元格的坐标 int row = table.rowAtPoint(p); IstatCellRenderer renderer = (IstatCellRenderer) table .getCellRenderer(row, 0); renderer.setCurrentRow(row); }
就是在单元格单击事件中取得cellRenderer后改变自定义的变量currentRow为鼠标所在单元格的行,然后再getTableCellRendererComponent方法中判断改变标题的颜色,代码如下:
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); IstatTableModel model = (IstatTableModel) table.getModel(); // 只读单元格行标题的颜色 if (column == 0) { System.out.println("renderer out row:" + row + " currentRow:" + currentRow); if (row == currentRow) {// 如果当前行等于选中行,则行标题的颜色设置为单元格选中的颜色 setBackground(table.getSelectionBackground()); } else { setBackground(table.getTableHeader().getBackground()); } } else { //作其他事情 } return this; }
但是监听器是在getTableCellRendererComponent方法后面执行的,所也无法实现,大家有没有好的意见。