问题描述
我试图使用ImageIcon
类将图像添加到jTable
单元格中,但是我进入了sun.awt.image.ToolkitImage@196a4632
单元格中应该在该单元格中显示图像的位置我尝试的代码:
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);
}
您需要在表模型上覆盖getColumnClass()
,并为带有ImageIcon
的列返回ImageIcon.class
.否则,渲染器将显示toString()
,因为默认的列类类型为Object
.请参见如何使用表:编辑器和渲染器. /p>
例如
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);
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 cellthe 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);
}
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);
这篇关于无法使用ImageIcon向jTable单元添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!