Search code examples
javaswingjtabletooltiplistener

How to add a tooltip to a cell in a jtable?


I have a table where each row represents a picture. In the column Path I store its absolute path. The string being kinda long, I would like that when I hover the mouse over the specific cell, a tooltip should pop-up next to the mouse containing the information from the cell.


Solution

  • I assume you didn't write a custom CellRenderer for the path but just use the DefaultTableCellRenderer. You should subclass the DefaultTableCellRenderer and set the tooltip in the getTableCellRendererComponent. Then set the renderer for the column.

    class PathCellRenderer extends DefaultTableCellRenderer {
        public Component getTableCellRendererComponent(
                            JTable table, Object value,
                            boolean isSelected, boolean hasFocus,
                            int row, int column) {
            JLabel c = (JLabel)super.getTableCellRendererComponent( /* params from above (table, value, isSelected, hasFocus, row, column) */ );
            // This...
            String pathValue = <getYourPathValue>; // Could be value.toString()
            c.setToolTipText(pathValue);
            // ...OR this probably works in your case:
            c.setToolTipText(c.getText());
            return c;
        }
    }
    
    ...
    pathColumn.setCellRenderer(new PathCellRenderer()); // If your path is of specific class (e.g. java.io.File) you could set the renderer for that type
    ...