将图像添加到jtable结果集中的哪些数据

时间:2012-11-06 14:56:37

标签: java swing netbeans jtable imageicon

  

可能重复:
  JAVA: Put Image in jTable Cell

我在向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;
  }


}

1 个答案:

答案 0 :(得分:3)

ImageIcon的{​​{3}}应该令人满意,但您需要覆盖getColumnClass()中的AbstractTableModel才能返回正确的类型。另请参阅此default renderer