Show images in some columns in jtable

imageicon, java, jtable, swing

Solution

Set the column class (for each column) as needed. As mentioned by @mKorbel, see also How to Use Tables - Concepts: Editors and Renderers.

Problem

I am making a `JTable` where the first two columns contain strings and the rest of the columns contain icons (specifically, objects of the class `ImageIcon`). I know how to do either, but how do I mix both in 1 table such that some columns return strings while others return icons? --EDIT-- explanation for code: data is a 2D string array. For the first two columns, i want them to be displayed as-it-is in the table. For all the rest of the columns, there are only two possible values, "Y" or "N". Now i want an ImageIcon to be displayed if there is a "Y", otherwise just leave it blank if there is a "N". (in case it helps to know, i am drawing a comparison table where i want a tick mark icon to be displayed if the value is "Y" otherwise just leave the cell empty if the value is "N") right now the output is like this: value of PATH_TO_ICON ("//home//....") in case of "Y" "javax.swing.ImageIcon@288e509b" in case of "N" ``` class MyTableModel extends AbstractTableModel { private Object[][] data; private String[] headers; public MyTableModel(String[][] data, String[] headers) { super(); this.data = data; this.headers = headers; } @Override public int getColumnCount() { return headers.length; } @Override public int getRowCount() { return data.length; } @Override public Object getValueAt(int row, int col) { if (col < 2) { return data[row][col]; } else { if (data[row][col].equals("Y")) { return new ImageIcon(PATH_TO_ICON); } else if(data[row][col].equals("N")) { return new ImageIcon(); } else return null; } } @Override public Class<?> getColumnClass(int col) { if (col < 2) { return String.class; } else { return ImageIcon.class; } } } ```

Original source