Share the post "Display ToolTip in JTable Cell If Text Is Truncated"
Setting a JTable to display tooltip is easy. But what if a JTable cell’s text is not truncated? A tooltip should only appear whenever a cell text is truncated which is denoted by three dots …
To add this functionality in a JTable object, you would need to get the cell width and compare it with the text’s width based on its font by using the FontMetrics class. Place this code insider the getTableCellRendererComponent() method of a TableCellRenderer object.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (c instanceof JLabel && value != null) { int availableWidth = table.getColumnModel().getColumn(column).getWidth(); availableWidth -= table.getIntercellSpacing().getWidth(); Insets borderInsets = getBorder().getBorderInsets(c); availableWidth -= (borderInsets.left + borderInsets.right); FontMetrics fm = getFontMetrics( getFont() ); String cellText = value.toString(); if (fm.stringWidth(cellText) > availableWidth) ((javax.swing.JLabel) c).setToolTipText(value.toString()); else ((javax.swing.JLabel) c).setToolTipText(null); } return c; } |
There you go. The tooltip will only appear when your mouse cursor hovers over a JTable cell where the text is truncated.