Search code examples
javaswingnetbeansjtableimageicon

add image to jtable which data in the resultset


Possible Duplicate:
JAVA: Put Image in jTable Cell

I got a question while I'm adding a image to jtable.I can add a single Image to jtable.but the question is I have more Images in my result set .I have tried while loop but it doesn't work. thank you all .

this is my code

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


}

Solution

  • The default renderer should be satisfactory for ImageIcon, but you need to override getColumnClass() in your AbstractTableModel to return the correct type. See also this answer.