Setting the mouse cursor for a particular JTable cell
Asked Answered
S

3

7

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?

Salad answered 7/4, 2009 at 19:7 Comment(0)
B
11

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.

Brandybrandyn answered 7/4, 2009 at 19:47 Comment(4)
I'll accept the answer because this is what we were doing already and it works. I was hoping to find something a little nicer though.Salad
yeah, this is more simpler. :DAstereognosis
This works well, except when the JTable is contained in a panel of a JTabbedPane. In that case, a Cursor set on the JTable has no effect. This appears to be a bug in Swing (Java SE 1.6.0_27).Selfacting
Is there a way can change the cursor only when it is over the cell text?Inlier
C
2

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);
}
Caesura answered 24/11, 2012 at 22:29 Comment(1)
This is the action to change the cursor, but it doesn't include the code about when to perform this action.Smokechaser
I
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());
}
Inlier answered 28/9, 2022 at 20:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.