2

可能重复:
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;
  }


}
4

1 回答 1

3

默认渲染器应该是令人满意的,ImageIcon但是您需要getColumnClass()在您的中重写AbstractTableModel以返回正确的类型。另请参阅此答案

于 2012-11-06T18:47:32.363 回答