我有这些数据:
我的问题是:
JTable
单元格的背景,并在鼠标释放事件时更改回正常背景?答案 0 :(得分:6)
假设您的意思是找到用于命中检测的单元格的矩形:
Rectangle cell = table.getCellRect(row, column, false);
对于背景更改,在mouseListener代码中,设置标记哪个单元格被击中,重新绘制按下/释放并实现自定义渲染器以检查标记。一些伪代码
void mousePressed(MouseEvent ev) {
// get the row/column from mouse location
int column = table.columnAtPoint(ev.getPoint());
int row = table.rowAtPoint(ev.getPoint());
// set some kind of marker, f.i. as client property
table.putClientProperty("hitColumn", column);
table.putClientProperty("hitRow", row);
// get the rectangle for repainting
Rectangle cell = table.getCellRect(column, row, false);
table.repaint(cell);
}
void mouseReleased(MouseEvent ev) {
// similar to reset the marker
....
table.repaint(cell);
}
// custom renderer extends DefaultTableCellRenderer
JComponent getTableCellRendererComponent(..., row, column ...) {
Integer hitColumn = table.getClientProperty("hitColumn");
Integer hitRow = ....
if (hitColumn != null && column == hitColumn && hitRow ....) {
setBackground(hitColor);
} else {
// force super to handle the background
setBackground(null);
}
return super.getTableCellRendererComponent(....);
}