Can't add image using ImageIcon to jTable cell

好久不见. 提交于 2019-11-27 08:38:16

问题


I trying to add image using ImageIcon class to jTable cell , but i get in the cell sun.awt.image.ToolkitImage@196a4632 where it supposed to display image in the cell the code i tried :

     JTable jTable;
 String[] columns={"Page No","Chapter","Image"};
 Object[][] rows={{1,4,null},{2,7,null}}}
 public Tab_ImgIcn(){
 ImageIcon icon=new ImageIcon(getClass().getResource("exit.png"));
           jTable= new JTable(rows, columns);
           jTable.setValueAt(icon.getImage(), 0,3);
           JScrollPane jps = new JScrollPane(jTable);
           frame.add(jps);
}

回答1:


You need to override getColumnClass() on the table model, and return ImageIcon.class for the column with the ImageIcon. If you don't, the renderer will show the toString(), as the default column class type will be Object. See How to use Tables: Editors and Renderers.

For example

ImageIcon icon=new ImageIcon(getClass().getResource("exit.png"));
String[] columns={"Page No","Chapter","Image"};
Object[][] rows={{1,4,icon},{2,7,icon}};

DefaultTableModel model = new DefaultTableModel(rows, columns) {
    @Override
    public Class<?> getColumnClass(int column) {
        switch(column) {
            case 0:
            case 1: return Integer.class;
            case 2: return ImageIcon.class;
            default: return Object.class;
        }
    }
};
JTable table = new JTable(model);


来源:https://stackoverflow.com/questions/25378231/cant-add-image-using-imageicon-to-jtable-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!