Search code examples
javaswingjtablecelltablecellrenderer

Find the JTable cell and paint it


I have these data:

  1. Row Number
  2. Column Number
  3. Cell Value

My questions are:

  1. How can I find the cell by using those data?
  2. How can I change the background of JTable cell on mouse press event and back to normal background on mouse release Event?
  3. Can i Highlight the JTable without user interaction, means clicking on some other JTable cell i want to highlight another JTable cell by using given information, is it possible?

Solution

  • 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(....);
     }