Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...