Java 在鼠标悬停时计算工具提示,而不是加载表格
我正在创建一个swing表单元格渲染器,它应该将图像显示为工具提示。这是基本的实现:Java 在鼠标悬停时计算工具提示,而不是加载表格,java,swing,tooltip,renderer,Java,Swing,Tooltip,Renderer,我正在创建一个swing表单元格渲染器,它应该将图像显示为工具提示。这是基本的实现: 图像存储在文件服务器上,并使用文档管理系统进行管理。我们使用一种方法使用这些文件的唯一文档id检索这些文件。此部分无法更改 创建包含图像Id和文件对象的哈希映射 渲染器检查HashMap中是否包含图像Id。如果是,将从HashMap加载图像。如果没有,则应下载图像 这是渲染器方法: @Override public Component getTableCellRendererComponent(JTable t
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
zebraPainter.paint(table, value, isSelected, hasFocus, row, column, this, false);
if (value != null) {
@SuppressWarnings({ "rawtypes", "unchecked" })
T bo = (T) (((DefaultBOTableModel) table.getModel()).getBusinessObject(row));
if (bo.getImageLink() != null) {
setToolTipText(getImageFile(bo.getImageLink()));
} else {
setToolTipText(null);
}
}
return this;
}
T是存储在JTable中的通用对象
这是生成工具提示HTML的方法
private String getImageFile(final Integer documentId) {
if (documentId != null) {
final DocumentService docService = ResourceManager.get(DocumentService.class);
// check whether the document is already stored in imageMap. Use this if yes, download the image
// and put in the map if no.
File image = imageMap.get(documentId);
if (image == null) {
File myImage = docService.retrieveDocumentFile(new KeyObject(documentId, -1));
imageMap.put(documentId, myImage);
image = imageMap.get(documentId);
}
// URL of the image.
URL url;
try {
url = image.toURI().toURL();
} catch (MalformedURLException e) {
throw new MespasRuntimeException("Error generating image tooltip", e);
}
return "<html><img src='" + url + "'/></html>";
} else {
return null;
}
}
仅当我在单元格上执行鼠标悬停以确保仅下载实际正在观看的图像时才调用 您需要
addMouseMotionListener
来检测鼠标何时悬停在图像上,然后您应该访问存储在单元格上的通用对象,以获取调用getImageFile()
的链接
第一个进程需要在mouseMoved
中设置一个条件,以便只计算从一个单元格到另一个单元格(而不是单元格内部)的移动
第二个需要作为JComponent
访问单元格才能设置工具提示图像。
:
getImageFile()
public static int rowh, colh;//global
...
table.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
int col = table.columnAtPoint(e.getPoint());
if (rowh != row || colh != col) { //movements from cell to cell inside the table.
rowh = row;
colh = col;
Object value = table.getModel().getValueAt(row, col);//get your Object value
TableCellRenderer cellRenderer = table.getCellRenderer(row, col);
Component rendererComponent = cellRenderer.getTableCellRendererComponent(table, null, false, true, row, col);
JComponent jcomp = (JComponent)rendererComponent;
//set the toolTip as you want.
T bo = (T) (((DefaultTableModel) table.getModel()).getBusinessObject(row));
if (bo.getImageLink() != null) {
jcomp.setToolTipText(getImageFile(bo.getImageLink()));
} else {
jcomp.setToolTipText(null);
}
}
}
@Override
public void mouseExited(MouseEvent e) {
rowh = -1;
colh = -1;
}
});