0

I have a JTable and any single row in it has associated a different tooltip when mouse hover a row. I have created a "filter" for this table; when it is applied it perfectly hides the rows need to be hidden but when I hover the mouse on the filtered rows, looks like the tooltip is referring to the row that occupied the same row position of the new current row.

For example:

Table

ROW 1 -> tooltip 1

ROW 2 -> tooltip 2

Apply Filter to Table:

ROW 2 -> tooltip 1

So ROW 2 is displaying the tooltip 1 instead of 2.

TableRowSorter<TableModel> sorter = (TableRowSorter<TableModel>) table.getRowSorter();
sorter.setRowFilter(RowFilter.regexFilter(text));

My table that extends JTable has:

@Override
public String getToolTipText(MouseEvent e) {
    final int rowIndex = rowAtPoint(e.getPoint());
    TableModel model = getModel();
    // take the value from the first column of the selected row
    String tip = (String) getModel().getValueAt(rowIndex, 0));
    return tip;
}

So it looks like using the model is not (quite obvious) updated respect to the filter. I tried using TableModel model = getRowSorter().getModel() too but without any luck.

How can I point to a correct "filtered model" to retrieve the correct row position?

UPDATE:

I have replaced the "rowIndex" code like this:

final int rowIndex = convertRowIndexToModel(rowAtPoint(e.getPoint()));

It partially solves the problem, but when some rows are added dynamically to the table with the filter applied and I hover new rows I get the exception (with relative API description):

IndexOutOfBoundsException -> if sorting is enabled and passed an index outside the range of the JTable as determined by the method getRowCount

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Randomize
  • 8,651
  • 18
  • 78
  • 133
  • works no issue, for better help sooner post an [SSCCE](http://sscce.org/), there must be another issue – mKorbel Nov 04 '12 at 22:02

2 Answers2

4

You need to convert the views row index to the model's row index

Have a look at JTable#convertRowIndexToModel

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • thank you very much for your suggestion. It almost solves the problem tho I have still some issue with it. Please see the update above. – Randomize Nov 04 '12 at 20:18
  • Make sure that you're not updating the table model out side of the Event Dispatching Thread, this will cripple the sorter/filter – MadProgrammer Nov 04 '12 at 23:27
2

You should not override that JTable#getToolTipText method. Just set the tooltip-text on the component returned by your renderer. The JTable will pick it up automatically. You can see this in the implementation of the getTooltipText method of the JTable

Robin
  • 36,233
  • 5
  • 47
  • 99