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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
...
- Oracle JTable tutorial on tooltips
回答2:
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;
}
};
回答3:
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.