Search code examples
javaimageswingjtablelistselectionlistener

Displaying Blob Value from JTable cell to JLabel


I have a ListSelectionListener that gets Blob value from a certain row cell and loads it to a JLabel. The issue here is that everytime i clicked on a row, it loads the image to the JLabel before highlighting the row. And there is a delay when loading the image. How can i resolve this issue?

      mytable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){

        @Override
        public void valueChanged(ListSelectionEvent e) {                                                                                              

               BufferedImage buffImg = null;
               ImageIcon imgIcon = null;
               Blob blob = (Blob) tableItem.getValueAt(selectedRow, 0);
               InputStream is = blob.getBinaryStream();                                               
               buffImg = ImageIO.read(is);                                                  
               imgIcon = new ImageIcon(buffImg.getScaledInstance(label.getWidth(), label.getHeight(),
                     Image.SCALE_SMOOTH));                                                  


                 label.setIcon(imgIcon);
         }

    });

Solution

  • To solve the problem, query ListSelectionEvent.getValueIsAdjusting() & only progress if it is false. If one row is selected and the user clicks a different row, there will be two events fired. One for the deselection of the first row, the 2nd for the selection of the alternate row.


    As an aside. I would strongly recommend storing the Image in the table as opposed to a Blob - so there is no potentially long running code on table row selection.