Find the JTable cell and paint it

前端 未结 1 934
迷失自我
迷失自我 2021-01-22 10:36

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
1条回答
  •  南方客
    南方客 (楼主)
    2021-01-22 11:29

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

    0 讨论(0)
提交回复
热议问题