我想将数据库中的blob显示为JTable列。 我的代码如下:
public JTable getTable(String table,String query)throws Exception{
JTable t1 = new JTable();
DefaultTableModel dm = new DefaultTableModel();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
String c[] = new String[cols];
for(int i=0;i<cols;i++){
c[i]=rsmd.getColumnName(i+1);
dm.addColumn(c[i]);
}
//get data from rows
Object row[]=new Object[cols];
while(rs.next()){
row[0] = rs.getString(1);
row[1] = rs.getString(2);
row[2] = rs.getString(3);
row[3] = rs.getString(4);
row[4] = rs.getString(5);
row[5] = rs.getString(6);
java.sql.Blob blob = rs.getBlob(7);
int blobLength = (int) blob.length();
byte[] blobAsBytes = blob.getBytes(1, blobLength);
ImageIcon picture = new ImageIcon(blobAsBytes);
row[6] = picture;
row[7] = rs.getString(8);
row[8] = rs.getString(9);
dm.addRow(row);
}
t1.setModel(dm);
con.close();
return t1;
}
当我运行此代码时,JTable会发送:javax.swing.ImageIcon@*numbers*
而不是图像本身。
答案 0 :(得分:2)
DefaultTableModel通过调用toString()
方法将任何对象显示为String。
如果你想改变它,你必须通过覆盖getColumnClass()
方法告诉DefaultTableModel列的内容是什么。
DefaultTableModel dm = new DefaultTableModel(){
public class<?> getColumnClass(int columnIndex){
return 6==columnIndex?ImageIcon.class, String.class;
}
};
但是JTable
可能没有ImageIcon
的DefaultRenderer,但仍会显示意外情况。在这种情况下,您还必须自己为类ImageIcon
设置DefaultRenderer。
https://docs.oracle.com/javase/tutorial/uiswing/components/table.html
答案 1 :(得分:0)
您可以添加显示图标的渲染器。这样的渲染器看起来像这样:
public class IconCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column ) {
Component c = super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column );
((JLabel) c).setIcon( (ImageIcon) value );
((JLabel) c).setText( "" );
return c;
}
}
您可以通过以下几种方式添加此渲染器:
为ImageIcon类注册渲染器:
table.setDefaultRenderer( ImageIcon.class, new IconCellRenderer( ) );
指定列的渲染器:
int imageViewIndex = table.convertColumnIndexToView( 6 ); // view index of ImageIcon data
table.getColumnModel( ).getColumn( imageViewIndex ).setRenderer( new IconCellRenderer( ) );
子类JTable并覆盖getCellRenderer:
final int imageModelIndex = 6; // model index of ImageIcon data
JTable table = new JTable( ) {
TableCellRenderer imageIconRenderer = new IconCellRenderer( );
@Override
public TableCellRenderer getCellRenderer( int row, int column ) {
if( convertColumnIndexToModel( column ) == imageModelIndex )
return imageIconRenderer;
else
return super.getCellRenderer( row, column );
}
};