Why does Table.getItem(Point) always return the item from column zero?
-
21-08-2019 - |
Question
I've implemented a class to give me a more flexible tooptip for the org.eclipse.swt.widgets.Table class. As I'm sure you all know, by default you get one tooltip for the whole table - and not individual tips for each cell.
My object creates a number of listeners to implement it's own location sensitive tooltip, however, when I call Table.getItem(Point) to get the TableItem (or cell) over which the mouse is hovering it always returns the cell from column 0 of the correct row.
The table in question is created by a TableViewer with this incantation ...
viewer = new TableViewer( parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION );
Wherever am I going wrong?
Solution
The answer, in the end is that TableItem represents a row, and not a cell within a row. This little method will fetch the column number for you ...
/**
* Get the column from the given TableItem and Point objects
* @param pt
* @param item
* @return -1 if no column is found
*/
public static int getColumn( Point pt, TableItem item )
{
int columns = item.getParent().getColumnCount();
for (int i=0; i<columns; i++)
{
Rectangle rect = item.getBounds (i);
if ( pt.x >= rect.x && pt.x < rect.x + rect.width ) return i;
}
return -1;
}
NB: Rectangle.intersects( Point ) can fail if you hover exactly over the table edges, so I've used a simple X comparison instead.