1

How to make JTable column which contains different types of data? (some cells contain images, some cells contain text)

Like this:

enter image description here

I tried to make CellRenderer but it doesn't work.

col.setCellRenderer(new DefaultTableCellRenderer() {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (value instanceof ImageIcon) {
            ImageIcon img = (ImageIcon) value;
            setIcon(img);
            setHorizontalAlignment(JLabel.CENTER);
        }
        else {
            setValue(value);
        }
        return this;
    }
});

It gives me this strange output:

enter image description here

Without renderer it outputs text and numbers fine but doesn't display images:

enter image description here

Alex P.
  • 3,697
  • 9
  • 45
  • 110
  • 1
    "*JTable: text and image in the same column"* Use a [`JLabel`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JLabel.html) as a [rendering component](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#renderer). The label supports both `ImageIcon` & text. – Andrew Thompson Dec 05 '13 at 09:42
  • no idea how is that possible, there are three ways, everyhhing depends of settings in your XxxTableModel – mKorbel Dec 05 '13 at 09:45
  • JTable has a default renderer for ImageIcon, if you cast it correctly, it should work. – Leo Pflug Dec 05 '13 at 09:46
  • Show us a snippet of your code where you add the ImageIcon to the table.(the row/column containing it) – Leo Pflug Dec 05 '13 at 09:52

2 Answers2

4
  • last screen_shots talking about ColumnClass isn't set correctly or isn't already set

  • overrided getColumnClass with Icon/ImageIcon.Class in XxxTabelModel,

  • then your Renderer is seems like as useless

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • getColumnClass? I want to make column with different data types (text, images) not one column with images and another with text. – Alex P. Dec 05 '13 at 09:54
  • yes no issue is possible two ways, 1) easiest to setIcon in Renderer by (for example) String value stored in XxxTableModel for this cell 2. Renderer/Editor aren't about Column, but about [Cell in Column](http://stackoverflow.com/a/16971334/714968), this is your (maybe by mistake) decision – mKorbel Dec 05 '13 at 09:59
  • notice don't forget convert View to Model for both a.m. ways in my last comment – mKorbel Dec 05 '13 at 10:01
2

JTable has a default renderer to render ImageIcon.

More about this here: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender

Leo Pflug
  • 544
  • 3
  • 15