0

I have a JFrame window that contains a few buttons. I would also like to add the video feed from javacv (opencv) into the middle of the frame. My current example puts the video onto a canvas. I am wondering how I can add the canvas to the center of the frame or if I can add the video to a JPanel or something else and then add it to the frame.

Any suggestions would be appreciated

import javax.swing.JFrame;
import javax.swing.JPanel;

import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.*;
import com.googlecode.javacv.OpenCVFrameGrabber;
import static com.googlecode.javacv.cpp.opencv_core.cvFlip;

public class demo_video extends JFrame {

 public static void main(String[] args) {
  //Create canvas frame for displaying webcam.
     CanvasFrame canvas = new CanvasFrame("Webcam"); 
  //Set Canvas frame to close on exit
     canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);   
     //Declare FrameGrabber to import output from webcam
     FrameGrabber grabber = new OpenCVFrameGrabber(0);  
     try {      
      //Start grabber to capture video
      grabber.start();      
      //Declare img as IplImage
      IplImage img;

      while (true) {
       //inser grabed video fram to IplImage img
       img = grabber.grab();

       //Set canvas size as per dimentions of video frame.
       canvas.setCanvasSize(grabber.getImageWidth(), grabber.getImageHeight()); 

       if (img != null) {      
         //Flip image horizontally
         cvFlip(img, img, 1);
        //Show video frame in canvas
        canvas.showImage(img);               
        }
       }
      }
     catch (Exception e) {      
     }
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
JonDog
  • 517
  • 7
  • 23
  • 1
    See [this example](http://stackoverflow.com/questions/13715921/how-to-center-jpanel-with-dynamic-size/13718410#13718410) for how to center a (resizable) component in the parent window. And this similar example with a [component centered within a `JScrollPane`](http://stackoverflow.com/a/13512826/418556). – Andrew Thompson Dec 05 '12 at 08:25
  • Does this work with a Canvas? I know how to add a JPanel to a JFrame. My real question is how to add a canvas to a JFrame. – JonDog Dec 05 '12 at 16:16
  • If you mean a `java.awt.Canvas` then 'not very well' in older JREs, but 'just fine' in newer ones. It comes down to [Mixing Lightweight & Heavyweight components](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html). OTOH if you mean a [`com.googlecode.javacv.CanvasFrame`](http://code.google.com/p/javacv/source/browse/src/main/java/com/googlecode/javacv/CanvasFrame.java?r=c10c4396e54151e5b968741c950161d4f5e43cdd) which is also a `JFrame` then - no. But you could have discovered that by trying it within the time it took me to locate the docs. for `CanvasFrame`. ;) – Andrew Thompson Dec 06 '12 at 01:34

0 Answers0