Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...