Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem lies with your TableModel, you have to tell the table that it has to render an image in that column overriding the <code>getColumnClass(int column)</code> method of the model.</p> <p>Look at this <a href="https://stackoverflow.com/a/4947154/2588463">answer</a> by camickr.</p> <p><strong>UPDATE</strong></p> <p>Minimal example of a JTable with an ImageIcon using DefaultTableModel's renderer to paint it. I borrowed the <code>updateRowHeights()</code> code from <a href="https://stackoverflow.com/a/1784601/2588463">this answer</a> again by camickr, without it the icon was bigger than the row and wasn't fully displayed.</p> <p>The important thing here is that now when the renderer calls <code>getColumnClass(1)</code>, it gets <code>ImageIcon.class</code> so the code to render icons will be executed. By default this method would return <code>Object.class</code> and the renderer would ignore the fact that it's an icon.</p> <pre><code>import java.awt.BorderLayout; import java.awt.Component; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; public class ImageIconTable { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ImageIconTable().initGUI(); } }); } public void initGUI() { JFrame frame = new JFrame(); DefaultTableModel tableModel = new DefaultTableModel() { @Override public Class getColumnClass(int column) { if (column == 1) return ImageIcon.class; return Object.class; } }; tableModel.addColumn("Row 1"); tableModel.addColumn("Icons Row"); tableModel.addRow(new Object[]{"This cell is an Object", new ImageIcon("icon.jpg")}); _table = new JTable(tableModel); updateRowHeights(); frame.add(new JScrollPane(_table), BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); } private void updateRowHeights() { try { for (int row = 0; row &lt; _table.getRowCount(); row++) { int rowHeight = _table.getRowHeight(); for (int column = 0; column &lt; _table.getColumnCount(); column++) { Component comp = _table.prepareRenderer(_table.getCellRenderer(row, column), row, column); rowHeight = Math.max(rowHeight, comp.getPreferredSize().height); } _table.setRowHeight(row, rowHeight); } } catch(ClassCastException e) {} } private JTable _table; } </code></pre> <p>It looks like this:</p> <p><img src="https://i.stack.imgur.com/dZgZt.png" alt="Table displaying an icon"></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload