How to display Image form JTable into JLabel or from database to JLabel using JTable mouse click event?

This question might have been asked here for couple of times, but I found some of them unsolved Retrieving image from mysql column to jlabel or to jtable.

Desired Output:

if I click any specific row containing image then it should display the image inside the JLabel, but if the row does not contain image then the label should display “No Photo Available”.

Below is the lines of codes which I’m currently using to display the image from JTable to the jlabelPhoto.

if(EmpDBTable.getValueAt(getData, 12) != null){
    try {               
         byte[] byteArray = (byte[]) EmpDBTable.getValueAt(getData, 12);
         ByteArrayInputStream bais = newByteArrayInputStream(byteArray);
         BufferedImage bImg = ImageIO.read(bais);
         ImageIcon icon = new ImageIcon(bImg.getScaledInstance(jLabelPhoto.getWidth(), jLabelPhoto.getHeight(), Image.SCALE_SMOOTH));
         jLabelPhoto.setIcon(icon);
         bais.close();
    } catch (Exception e) {
         JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}else{
    jLabelPhoto.setText("No Photo Available");
}

This code allows to me display image into the label properly with scale, but the problem is if I click the row that has no image in it then the previous image still appearing on the label.

Here is the attached link of the video for proper illustration. https://vimeo.com/user101485383/review/351884404/57a10f86af

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

Your problem could possibly because you forgot to set the JLabel’s Icon to null in the else block:

} else {
    jLabelPhoto.setText("No Photo Available");
    jLabelPhoto.setIcon(null);  // need to add this
}

If this doesn’t fix the problem then you will likely need to debug the if block condition:

if(EmpDBTable.getValueAt(getData, 12) != null) {

Perhaps the data held is not an image, but also not null, but since you hold all the data and the code, it will be up to you to debug this if need be.