6

I have a JTable with a set of uneditable cells and I want all the cells in a particular column to have a different mouse cursor displayed whilst the mouse is hovering over them. I am already using a custom renderer and setting the cursor on the renderer component doesn't seem to work (as it does for tooltips).

It does seem to work for editors.

Is this not possible in JTable when your cell is not being edited or am I missing something?

Jonas
  • 121,568
  • 97
  • 310
  • 388
Tom Martin
  • 2,498
  • 3
  • 29
  • 37

3 Answers3

10

Add a MouseMotionListener to the JTable and then on mouseMoved() determine which column it is using JTable's columnAtPoint() and if it's the particular column you are after, setCursor() on the JTable.

Kevin Herron
  • 6,500
  • 3
  • 26
  • 35
1

Here is one way of changing the cursor at a particular column in JTable:

if(tblExamHistoryAll.columnAtPoint(evt.getPoint())==5)
{
    setCursor(Cursor.HAND_CURSOR); 
}
else
{
    setCursor(0);
}
Marvo
  • 17,845
  • 8
  • 50
  • 74
  • This is the action to change the cursor, but it doesn't include the code about when to perform this action. – daifei4321 Nov 03 '22 at 10:28
0

I wanted to only change the cursor when the mouse was over the text in the cell. This was my solution:

private JTable table = ...;

@Override
public void mouseMoved(MouseEvent e) {
    Point point = e.getPoint();

    int column = table.columnAtPoint(point);
    int row = table.rowAtPoint(point);

    Component component = table.getCellRenderer(row, column).getTableCellRendererComponent(table,
            getValueAt(row, column), false, false, row, column);
    Dimension size = component.getPreferredSize();

    Rectangle rectangle = table.getCellRect(row, column, false);
    rectangle.setSize(size);

    if (rectangle.contains(point)) {
        table.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        return;
    }

    table.setCursor(Cursor.getDefaultCursor());
}
Cardinal System
  • 2,749
  • 3
  • 21
  • 42