Search code examples
javaswingjtableimageicontablecellrenderer

Image not showing in Jtable with renderer


I have created a CellRenderer for my table. It works fine if the image is with small size. However , if it's a little large it shows me blank space

 public  class ImageRenderer extends DefaultTableCellRenderer {
 JLabel lbl = new JLabel();
 JButton bouton ;

List<Commentaire> liste;
  ImageIcon icon ;
  Commentaire commentaire;


   // Increase the height of each row by 50% so we can see the whole
   // image.

    public ImageRenderer() {
         liste=  new CommentaireDAO().findCommentaire();
    }

@Override
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {

 if (column==0){
     int id = (int)value;
     Client c = new ClientDAO().findClientById(id);
     InputStream photo= c.getPhoto();
     try {
            if (photo != null) {
                int size = photo.available();
                byte[] imageBytes = new byte[size];
                photo.read(imageBytes);
                ImageIcon icon = new ImageIcon(imageBytes);
                Image img = icon.getImage();
                BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
                Graphics g = bi.createGraphics();
                g.drawImage(img, 0, 0, 50, 50, null);
                ImageIcon newIcon = new ImageIcon(bi);
                lbl.setSize(250,250);
                lbl.setHorizontalAlignment(CENTER);
                lbl.setIcon(newIcon);
            }else{
                System.out.println("photo null");
            }
        } catch (IOException ex) {
            Logger.getLogger(OffreClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        }

      }

Is there any method to resize the image to fit in the column ?


Solution

  • The code in a renderer should be very fast and efficient. You should not be doing processing to create the image every time the cell is rendered.

    Instead you should be storing an ImageIcon in the TableModel. Then you override the getColumnClass(...) method of the TableModel to return Icon.class and the JTable will used the default table renderer for the Icon.

    If you want to dynamically scale the Icon you can add a Stretch Icon to the TableModel.