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

2019-02-08 06:59发布

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.

3条回答
Evening l夕情丶
2楼-- · 2019-02-08 07:39

You say you store an absolute path in a cell. You are probably using a JLabel for setting absolute path string. Suppose you have a label in your cell, use html tags for expressing tooltip content:

JLabel label = new JLabel("Bla bla");
label.setToolTipText("<html><p>information about cell</p></html>");

setToolTipText() can be used for some other Swing components if you are using something other than JLabel.

查看更多
淡お忘
3楼-- · 2019-02-08 08:02

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
...
查看更多
啃猪蹄的小仙女
4楼-- · 2019-02-08 08:06

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;
            }
        };
查看更多
登录 后发表回答