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

40,289

Solution 1

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
...

Solution 2

Just use below code while creation of JTable object.

JTable auditTable = new JTable(){

            //Implement table cell tool tips.           
            public String getToolTipText(MouseEvent e) {
                String tip = null;
                java.awt.Point p = e.getPoint();
                int rowIndex = rowAtPoint(p);
                int colIndex = columnAtPoint(p);

                try {
                    tip = getValueAt(rowIndex, colIndex).toString();
                } catch (RuntimeException e1) {
                    //catch null pointer exception if mouse is over an empty line
                }

                return tip;
            }
        };
Share:
40,289
Pantaziu Cristian
Author by

Pantaziu Cristian

Junior Java Programmer

Updated on July 28, 2022

Comments

  • Pantaziu Cristian
    Pantaziu Cristian almost 2 years

    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.