Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

java - Can't add image using ImageIcon to jTable cell

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...