根据数据库值动态加载jTable中的Image

时间:2014-05-07 13:50:56

标签: java swing dynamic jtable

我正在尝试根据数据库值在jTable中加载图像。

String query = "SELECT ID, CATEGORY FROM TATTOO_LIB ORDER BY ID DESC";
try {
    conn = new data.connection().db();
    stmtt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmtt.executeQuery(query);
    while (rs.next()) {

        //I donot know how to write these lines here...

        File f = new File("C:/img/" + rs.getString(1) + ".jpg");
        ImageIcon icon = new ImageIcon(f);
        model.addRow(new Object[]{icon, rs.getString(1), rs.getString(2)});


    }
} catch(SQLException e ) {
    JOptionPane.showMessageDialog(null, "Error In Connection!!");
} finally {
    try {
        stmtt.close();
        rs.close();
        conn.close();
    } catch (SQLException e) {
    }

}

如何根据数据库值在第一列中加载图像。 我尝试关注thisthis。但我在某个地方迷路了。请帮忙。

1 个答案:

答案 0 :(得分:2)

覆盖表模型的getColumnClass(),以便可以正确呈现ImageIcon。请点击How to Use Tables - Concepts: Editors and Renderers

了解更多信息
    DefaultTableModel model = new DefaultTableModel(colNames, 0) {
        @Override
        public Class<?> getColumnClass(int col) {
            switch(col) {
                case 0: return ImageIcon.class;
                default: return String.class;
            }
        }
    };

ImageIcon也不接受File参数。您可以使用ImageIO.read()获取Image以传递给ImageIcon,但

File f = new File("C:/img/"+rs.getString(1)+".jpg");
Image image = ImageIO.read(f);
ImageIcon icon = new ImageIcon(image);

只能将字符串文件路径传递给ImageIcon,但ImageIO会抛出异常,路径不正确,这很有帮助

您可能需要相应地设置行高和列宽,

table.setRowHeight(height);
TableColumn column = table.getColumn("ColumnIdentifier");
column.setWidth(150);