Rectangle not drawn in detected face in java

Currently,I’m dealing with a project based on face detection and recognition..I’m using opencv. My problem is Jpanel contains camera visuals with no rectangle on detected face but when captured image is saved on training set , saved image contains rectangle on detected face.

What might be the problem?

package snap;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
 import javax.swing.ImageIcon;
 import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;


public class SnapShot extends javax.swing.JFrame {

/**
 * Creates new form SnapShot
 */

   private DaemonThread myThread = null;
    int count = 0;
   VideoCapture webSource = null;
  int c=0;
   Mat frame = new Mat();
   MatOfByte mem = new MatOfByte();
   private CascadeClassifier faceDetector = new CascadeClassifier(
   "D:/opencv/build/etc/haarcascades/haarcascade_frontalface_alt.xml");
    private MatOfRect detectedFaces = new MatOfRect();
    JLabel panel1;
    public SnapShot() {

    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    panel = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    pause = new javax.swing.JButton();
    save = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    panel.setBackground(new java.awt.Color(255, 255, 255));

    javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
    panel.setLayout(panelLayout);
    panelLayout.setHorizontalGroup(
        panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 0, Short.MAX_VALUE)
    );
    panelLayout.setVerticalGroup(
        panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 449, Short.MAX_VALUE)
    );

    jButton1.setBackground(new java.awt.Color(255, 51, 51));
    jButton1.setText("Start Camera");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    pause.setBackground(new java.awt.Color(0, 204, 51));
    pause.setText("Capture");
    pause.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            pauseActionPerformed(evt);
        }
    });

    save.setBackground(new java.awt.Color(255, 204, 255));
    save.setText("Add to Training set");
    save.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            saveActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(141, Short.MAX_VALUE)
            .addComponent(jButton1)
            .addGap(18, 18, 18)
            .addComponent(pause)
            .addGap(18, 18, 18)
            .addComponent(save)
            .addGap(251, 251, 251))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(save)
                .addComponent(pause)
                .addComponent(jButton1))
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
     webSource =new VideoCapture(0);
        myThread = new DaemonThread();
        Thread t = new Thread(myThread);
        t.setDaemon(true);
        myThread.runnable = true;
        t.start();
         jButton1.setEnabled(false);  //start button
        pause.setEnabled(true);  // stop button
}                                        

private void pauseActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
    myThread.runnable = false;
        pause.setEnabled(false);   
        jButton1.setEnabled(true);

        webSource.release();
}                                     
private BufferedImage mat2BufferedImage(Mat m) {
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if (m.channels() > 1) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }
    int bufferSize = m.channels() * m.cols() * m.rows();
    byte[] b = new byte[bufferSize];
    m.get(0, 0, b); // get all the pixels
    BufferedImage img = new BufferedImage(m.cols(), m.rows(), type);
    final byte[] targetPixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
    System.arraycopy(b, 0, targetPixels, 0, b.length);
    return img;
}
private void saveActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:

    String timeStamp = new SimpleDateFormat("yyyyMMdd_hhmmss_a").format(new Date());
     File file=   new File("C:/Users/HP/Desktop/FaceImages");
 File outputfile ;
 if(!file.exists())
 {
     file.mkdir();
    outputfile = new File("C:/Users/HP/Desktop/FaceImages/"+timeStamp+".png"); 
        try {
            ImageIO.write(mat2BufferedImage(frame), "png", outputfile);
        } catch (IOException ex) {
            Logger.getLogger(SnapShot.class.getName()).log(Level.SEVERE, null, ex);
        }
 }
 else{
   outputfile = new File("C:/Users/HP/Desktop/FaceImages/"+timeStamp+".png"); 
        try {
            ImageIO.write(mat2BufferedImage(frame), "png", outputfile);
        } catch (IOException ex) {
            Logger.getLogger(SnapShot.class.getName()).log(Level.SEVERE, null, ex);
        }
 }
 dispose();
}                                    

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(SnapShot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(SnapShot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(SnapShot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(SnapShot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
            new SnapShot().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JPanel panel;
private javax.swing.JButton pause;
private javax.swing.JButton save;
// End of variables declaration                   

 class DaemonThread implements Runnable
{
protected volatile boolean runnable = false;

@Override
public  void run()
{
    synchronized(this)
    {
        while(runnable)
        {
            if(webSource.grab())
            {
            try
                    {
                        webSource.retrieve(frame);
            Imgcodecs.imencode(".bmp", frame, mem);
            Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));

           BufferedImage buff = (BufferedImage) im;
           Graphics g=panel.getGraphics();

            if (g.drawImage(buff, 0, 0, getWidth(), getHeight() -150 , 0, 0, buff.getWidth(), buff.getHeight(), null))
 // detect the faces
                            if(webSource.isOpened()&& webSource.read(frame))
                            {
                                c++;

                                 faceDetector.detectMultiScale(frame, detectedFaces);
        // detect the eyes
       // eyeDetector.detectMultiScale(mat, detectedEyes);
        // place a green rectangle over each face
        for (Rect face : detectedFaces.toArray()) {
               System.out.println(c);
            if(face.height == 0 && face.width == 0){

                continue;
            }

            Imgproc.rectangle(frame, new Point(face.x, face.y), new Point(face.x + face.width, face.y + face.height),new Scalar(0, 255,0), 3);
        }
                            }


            if(runnable == false)
                        {

                System.out.println("Going to wait()");
                this.wait();
            }
         }
         catch(Exception ex)
                     {
            System.out.println("Error");
                     }
            }
        }
    }
 }
 }

}

`