如何向jtable中的单元格添加工具提示?

2022-09-01 12:29:59

我有一个表格,其中每行代表一张图片。在“路径”列中,我存储其绝对路径。字符串有点长,我希望当我将鼠标悬停在特定单元格上时,应该在包含单元格信息的鼠标旁边弹出一个工具提示。


答案 1

只需在创建JTable对象时使用以下代码即可。

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;
            }
        };

答案 2

我假设您没有为路径编写自定义,而只是使用 .您应该在 中对 进行子类化并设置工具提示。然后设置列的呈现器。CellRendererDefaultTableCellRendererDefaultTableCellRenderergetTableCellRendererComponent

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