JAVA: Put Image in jTable Cell

自作多情 提交于 2019-11-27 15:22:50

JTable already provides a default renderer for images. You just need to tell the table what type of data is contained in each column and it will choose the best renderer:

a) override the getColumnClass() method of the JTable or the TableModel to return the class of data in the column. In this case you should return an Icon.class.

b) add an ImageIcon to the table model.

Now the JTable will use the default Icon renderer for that column.

Hmm: jTable1.getColumnModel().getColumn(0).setCellRenderer(new ImageRenderer()); perhaps?

Here's the relevant extract of some quick test code I put together to quickly verify my guess. It displays icons from a folder (it assumes all files in a folder are icons, so you should test it with something like an XDG icon theme sub directory). Install table model first then add the cell renderer on the columns:

class Renderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent (JTable table,
                                                    Object value,
                                                    boolean isSelected,
                                                    boolean hasFocus,
                                                    int row, int column) {
        if(isSelected) {
            this.setBackground(table.getSelectionBackground());
            this.setForeground(table.getSelectionForeground());
        }
        else {
            this.setBackground(table.getBackground());
            this.setForeground(table.getForeground());
        }
        if(column == 0) {
            this.setText(list[row]);
        }
        else {
            // edit as appropriate for your icon theme
            this.setIcon(new ImageIcon("/usr/share/icons/default.kde4/16x16/apps/"+list[row]));
        }
        return this;
    }

}
class Model extends DefaultTableModel {

    @Override
    public boolean isCellEditable (int row, int column) {
        return false;
    }

    @Override
    public Object getValueAt (int row, int column) {
        return list[row];
    }

    @Override
    public int getRowCount () {
        return list.length;
    }

    @Override
    public int getColumnCount () {
        return 2;
    }

    @Override
    public String getColumnName (int column) {
        return column == 0? "Name" : "Preview";
    }

    @Override
    public Class<?> getColumnClass (int columnIndex) {
        return String.class;
    }
}
// edit base directory as appropriate for your icon theme of choice
static String[] list=new File("/usr/share/icons/default.kde4/16x16/apps/").list();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!