Search code examples
javaimageswingjlabel

How to dynamically update image to jlabel


I am trying to create a simple application which can take an image from web cam and display it in a jlabel. but I is not working. I can't understand the reason. my complete project uploaded to here. I use this library to take the image, following code does it.

// get default webcam and open it
    Webcam webcam = Webcam.getDefault();
    webcam.open();

    // get image
    BufferedImage image = webcam.getImage();

    try {
        // save image to PNG file
        ImageIO.write(image, "PNG", new File("test.png"));
    } catch (IOException ex) {
        Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
     webcam.close();

after taking the image I wrote the following code to display the image to jlabel

String path = "test.png";
imageLbl.setIcon(null);
imageLbl.setIcon(new ImageIcon(path));
imageLbl.revalidate();
imageLbl.repaint();
imageLbl.update(imageLbl.getGraphics());

if there is an image already then it will display to the jlabel. but most reasonlly taken image is not shown. it's hard to explain the situation, I appreciate if you can download and check my project here.


Solution

  • You can use below code to dynamically update image to jlabel.

      String path = "test.png";
      imageLbl.setIcon(null);
        try {
          BufferedImage img=ImageIO.read(new File(path));
            imageLbl.setIcon(new ImageIcon(img));
            imageLbl.revalidate();
            imageLbl.repaint();
            imageLbl.update(imageLbl.getGraphics());
        } catch (IOException ex) {
    
        }