可能重复:
JAVA:将图像放入 jTable 单元格
我在将图像添加到 jtable 时遇到了一个问题。我可以将单个图像添加到 jtable。但问题是我的结果集中有更多图像。我尝试了 while 循环,但它不起作用。谢谢你们 。
这是我的代码
public void setableimage(String name) throws SQLException
{
try
{
ImageIcon ico;
DBConnManager dbconn = new DBConnManager();
Connection conn = dbconn.getConnect();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("SELECT image,F_name,L_name FROM person WHERE F_name LIKE '"+name+"%' ");
while(rst.next())
{
byte[]imagedata = rst.getBytes(1); // get image data to byte array
String perName = " "+rst.getString(2).toString()+" "+rst.getString(3).toString(); // get fersons name
ico = new ImageIcon(imagedata); // create image icon
MyTableModel model = new MyTableModel(); // create MyTableModel
ImageRender im = new ImageRender(); // create ImageRender object
im.setIcon(ico); // set the icon like Person's image
im.setDes(perName); // set the image description like First name and Last name
jTable1.setModel(model);
jTable1.setRowHeight(80);
jTable1.getColumnModel().getColumn(0).setCellRenderer(im);
}
}
catch (SQLException ex) {
System.out.println(ex);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
public class MyTableModel extends AbstractTableModel{
@Override
public int getRowCount() {
return 1;
}
@Override
public int getColumnCount() {
return 1;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return ""+(rowIndex*columnIndex);
}
}
///////////////////////////////////imageRender class
public class ImageRender extends DefaultTableCellRenderer
{
JLabel lbl = new JLabel();
ImageIcon icon ;
String des;
public void setDes(String des)
{
this.des = des;
}
public void setIcon(ImageIcon icon)
{
this.icon = icon;
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
lbl.setText(des);
lbl.setIcon(icon);
return lbl;
}
}