-1

I have this webcam program that runs in a JFrame. Whenever I close the frame, it prints out "Closed" like it's supposed to, but my IDE says that is still running. Why is this and how do I fix it? I am not running any threads anywhere in the program. This doesn't have anything to do with the default close operation as I have tested for that already.

public class Webcam extends JPanel {

private static BufferedImage image;

public Webcam() {
  super();
}

public static void main(String args[]) {
  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

  JFrame frame = new JFrame("Webcam");
  Webcam panel = new Webcam();

  // Initialize JPanel parameters
  //frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  frame.setSize(1080, 720);
  frame.setContentPane(panel);
  frame.setVisible(true);
  frame.addWindowListener(new WindowAdapter()
  {
     @Override
     public void windowClosing(WindowEvent e)
     {
        System.out.println("Closed");
        e.getWindow().dispose();
        System.exit(0);
     }
  });
  Mat currentImage = new Mat();

  VideoCapture capture = new VideoCapture(0);
  if(capture.isOpened()) {
     // Infinitely update the images
     while(true) {
        // VideoCapture returns current Mat
        capture.read(currentImage);
        if(!currentImage.empty()) {
           frame.setSize(currentImage.width() + 40, currentImage.height() + 60);
           image = panel.matrixToBuffer(currentImage);
           // Update the panel
           panel.repaint();
        }
        else {
           System.out.println("Error: no frame captured");
           frame.dispose();
           System.exit(0);
           break;
        }
     }
  }
  return;

}

Lukas Strobel
  • 108
  • 1
  • 5
  • 5
    Possible duplicate of [JFrame Exit on close Java](http://stackoverflow.com/questions/7799940/jframe-exit-on-close-java) – nhouser9 Apr 04 '17 at 04:17
  • The main reason is because there's still a non-daemon thread running. You could have a look at using ['JFrame#setDefaultCloseOperation`](https://docs.oracle.com/javase/8/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation-int-) and passing `EXIT_ON_CLOSE`, but I'd have a look at see if you can find out why there is still a running thread – MadProgrammer Apr 04 '17 at 04:19
  • Can't reproduce. After stripping `Mat currentImage = new Mat();` and whatever behind it, I'm able to launch it in my IDEA and eclipse, yet closing the frame with x button shut the program. – glee8e Apr 04 '17 at 04:22
  • Even manually adding a forever-running thread, be it daemon or not, won't change anything. – glee8e Apr 04 '17 at 04:28

1 Answers1

0

Okay, while I appreciate all of the helpful comments, the issue was that the VideoCapture had an internal thread running, and adding capture.release() to my listener fixed it.

Lukas Strobel
  • 108
  • 1
  • 5