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

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

我假设您没有为路径编写自定义CellRenderer ,只是使用DefaultTableCellRenderer 。 您应该对DefaultTableCellRenderer子类化,并在getTableCellRendererComponent设置工具提示。 然后为列设置渲染器。

 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 = ; // 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 (eg java.io.File) you could set the renderer for that type ... 
  • 有关工具提示的Oracle JTable教程

只需在创建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; } }; 

您说您在单元格中存储绝对路径。 您可能正在使用JLabel来设置绝对路径字符串 。 假设您的单元格中有标签,请使用html标签表示工具提示内容:

 JLabel label = new JLabel("Bla bla"); label.setToolTipText("

information about cell

");

如果您使用的不是JLabel, setToolTipText()可用于其他一些Swing组件。