Find the JTable cell and paint it

◇◆丶佛笑我妖孽 提交于 2019-12-02 01:13:00

Assuming you mean to find the rectangle of the cell for hit detection:

 Rectangle cell = table.getCellRect(row, column, false);

For background changing, in your mouseListener code, set a marker which cell was hit, repaint on pressed/released and implement a custom renderer which checks for the marker. Some pseudo-code

 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(....);
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!