I added an Image in JTable row mentioned in http://www.java2s.com/Code/Java/Swing-JFC/RenderinganimageinaJTablecollumn.htm. But now I want to add a MouseListener to this particular Image. How to achieve the same
Asked
Active
Viewed 266 times
1 Answers
3
not directly supported, not even on a stand-alone JLabel. So there are two problems to solve
- get the region of the icon on the label
- get the region of the rendering component in the table
For the first, you can re-layout the label to get hold of the Rectangle which contains the icon (this is what BasicLabelUI does internally):
protected String layoutCL(
JLabel label,
FontMetrics fontMetrics,
String text,
Icon icon,
Rectangle viewR,
Rectangle iconR,
Rectangle textR)
{
return SwingUtilities.layoutCompoundLabel(
(JComponent) label,
fontMetrics,
text,
icon,
label.getVerticalAlignment(),
label.getHorizontalAlignment(),
label.getVerticalTextPosition(),
label.getHorizontalTextPosition(),
viewR,
iconR,
textR,
label.getIconTextGap());
}
for the second, ask the table for the cell rectangle at mouse position, and check whether the icon would be hit assuming the label would be added (and filling) the cell
int row = table.rowAtPoint(e.getPoint());
int column = table.columnAtPoint(e.getPoint());
Rectangle cellRect = table.getCellRect(row, column, false);
JLabel label = (JLabel) table.prepareRenderer(table.getRenderer(row, column), row, column);
Rectangle viewR = new Rectangle(0, 0, cellRect.width, cellRect.height);
Rectangle iconR = new Rectangle();
Rectangle textR = new Rectangle();
// call method above and do some math to translate the mouseEvent relative to the cell
-
1+1 This related [example](http://stackoverflow.com/questions/3597550/ideal-method-to-truncate-a-string-with-ellipsis/3597688#3597688) intercepts the call to inspect the geometry. – trashgod Nov 14 '11 at 11:53