Java - Is it possible to put an image and a String in the same JTable cell?
Asked Answered
C

1

3

I know how to put a String into a JTable cell, and I know how to put an image into a JTable cell. But is it possible to put an image and a String into the SAME JTable cell?

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. 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.

Carey answered 4/3, 2013 at 18:52 Comment(1)
See the question #1292448Denazify
W
4

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());
Wroughtup answered 4/3, 2013 at 19:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.