Tooltip on JTable cells (take 2)
In a previous post, I explain how to add tooltips to JTable cells. Armand Bendananff told, in a comment, that a better way is to override the table's getToolTipText method as in:
public String getToolTipText(MouseEvent event) { Point p = event.getPoint(); // Locate the renderer under the event location int colIndex = columnAtPoint(p); int rowIndex = rowAtPoint(p); String tooltip = "some value based on the row/col"; return tooltip; }
Long lines in Java Tooltips (or multiline tooltips)
Do you want to show a tooltip with more than one line? Are your tooltips too large to fit in one line? The solution is easier than you think. Tooltips, in Java, accept HTML code:
jcomponent.setToolTipText("HTML tooltip");
It isn't a Firefox, but is very powerful. And, when I said HTML, I also think about CSS. So, you can set your tooltips using this evil cheat:
<html><body> <strong><div style="width: 300px; text-justification: justify;"></strong> Blah Blah Blah (repeat "blah" 100 times) </div> </html></body>
Have you seen automatic line breaks and the justification? Oh, yeah!
BTW, do you remember old days, when you couldn't believe WordPad didn't have justified text?
Tooltip on JTable cells
This is a easy one (but it is not obvious): how to define tooltips in JTable's cells. Just create a class like this one:
public class ToolTipTable extends JTable { @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); if (c instanceof JComponent) { JComponent jc = (JComponent) c; jc.setToolTipText((String) getValueAt(row, column)); } return c; } }
This example will set cells' tooltip to its own content. Very useful if you have large contents on small cells.