Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

java - Displaying images from MySQL database on a single column of JTable

I'm trying to display images retrieve from MySQL database of blob datatype. Could not figure out what is the problem that causes the image column to display data like this [B@29b8e4f7 instead of image icon.

DefaultTableModel model = new DefaultTableModel(new Object[]{
    "image", "item_name", "quantity","price", "category", "color", "size"}, 0){
        @Override
        public Class<?> getColumnClass(int column) {
            switch(column){
                case 0: return ImageIcon.class;
                default: return String.class;
            }
        }
    };

    myTable.setModel(model);

...

         ResultSet rs = database.getRS();

            int columns = rs.getMetaData().getColumnCount();

            while(rs.next()){
                Object[] row = new Object[columns];
                for(int i = 1; i <= columns; i++){                        
                    row[i-1] = rs.getObject(i);

                }
                DefaultTableModel defmodel = (DefaultTableModel) tableItem.getModel();
                defmodel.insertRow(rs.getRow()-1, row);

            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you used preparedstatement.setBlob(1, InputStream); to store the image, I have to assume that you stored the physical image file/format and not just the pixel data.

You need to read back this image format and convert to a supported image format for Swing/Java.

Start by getting a Blob reference to the database field...

Blob blob = rs.getBlob(1);

Once you have a Blob, you can use it's binary InputStream and read the data...

BufferedImage image = null;
try (InputStream is = blob.getBinaryStream()) {
    image = ImageIO.read(is);
} catch (IOException exp) {
    exp.printStackTrace();
}

Now, you can make it an ImageIcon using new ImageIcon(image) and put this within your table model...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...