我正在尝试根据数据库值在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) {
}
}
答案 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);