简体   繁体   English

Java-是否可以在同一JTable单元格中放置图像和字符串?

[英]Java - Is it possible to put an image and a String in the same JTable cell?

I know how to put a String into a JTable cell, and I know how to put an image into a JTable cell. 我知道如何将字符串放入JTable单元格,并且我知道如何将图像放入JTable单元格。 But is it possible to put an image and a String into the SAME JTable cell? 但是是否可以将图像和字符串放入SAME JTable单元中?

The reason for this is that I have a 'status' column in my JTable, which at the moment contains either a green, amber or red image. 原因是我的JTable中有一个“状态”列,此列目前包含绿色,琥珀色或红色图像。 And in order to fulfill the design requirement, I need to add some explanatory text alongside each image (so the text next to the green image would be "Online", the text next to the amber image would be "Unknown" and the text next to the red image would be "Offline"). 并且为了满足设计要求,我需要在每个图像旁边添加一些说明性文本(因此绿色图像旁边的文本将是“在线”,琥珀色图像旁边的文本将是“未知”,下一个文本到红色图像将是“脱机”)。 I need to do this in a single column (or what looks/behaves like a single column) rather than two columns. 我需要在单列(或看起来/行为像单列)而不是两列中执行此操作。

I have researched this, but found no info at all. 我已经对此进行了研究,但根本找不到任何信息。

Yes. 是。

You need to use a custom cell renderer. 您需要使用自定义单元格渲染器。 Check out How to use Tables for more details. 请查看如何使用表格以获取更多详细信息。

You actually have two choices, you could simply set the icon and the text of the cell or you could use the renderers tooltip text instead... 实际上,您有两种选择,您可以简单地设置图标和单元格的文本,也可以使用渲染器工具提示文本...

public class IconTextCellRemderer extend DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table,
                                  Object value,
                                  boolean isSelected,
                                  boolean hasFocus,
                                  int row,
                                  int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        setText(...);
        setIcon(...);
        setToolTipText(...);
        return this;
    }
}

Of course you need to apply the renderer to the column... 当然,您需要将渲染器应用于列...

TableColumnModel tcm = table.getColumnModel();
tcm.getColumn(x).setCellRenderer(new IconTextCellRemderer());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM