Catch(NoResponseException nre) {nre.getTopic().rethrow();}

Maybe my previous thread's title ("Scoping paradox, or How I Learned to Love the NPE") just didn't do it for anybody, or maybe everyone is at the r'l thread. Anyway...
The basic problem is one of a non-null reference being passed in as an argument and being read as null...
http://forum.java.sun.com/thread.jsp?forum=31&thread=391348&tstart=0&trange=50

By the way, there is a Duke Dollar available in the aforementioned thread. It's the only one I have to give (wait, let me check...yep!), and no one has really solved the problem yet.

Similar Messages

  • Catching Errors: opinions needed

    Under what conditions should a program try to catch Errors (not Exceptions) ? The docs for the Error class read:
    "An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch."
    However, nothing enforces the fact that I should not try to catch an Error. I can catch a StackOverFlowError, ExceptionInInitializerError, etc. just as I would catch any Exception class.
    Everything I have read talks plenty about Exception handling, but basically nothing about Error handling.
    My questions are: 1) Why doesn't the JVM prevent me from catching Errors? 2) Under what conditions should I try to catch Errors? 3) What are good practices for handling Errors?

    My questions are: 1) Why doesn't the JVM prevent me from catching Errors? In case you need to catch them.
    2) Under what conditions should I try to catch Errors?When you want to perform an action when a specific error occurs.
    An action I perform is to shutdown my server when an OutOfMemoryError or StackOverflowError occurs. This is required as an Error only results in the end of the thread which threw it. The other threads can keep running, leaving a running but unless application, like a zombie. Under this condition, if the application is not working it should shutdown. e.g. System.exit();
    3) What are good practices for handling Errors?When you catch an erro you should rethrow it. (I don't always, but this is considered good practice)

  • Errors in code that captures images from webcam

    Here is the code
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture; // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture; // JMF 2.1.1e version
    public class JWebCam extends JFrame
    implements WindowListener, ComponentListener
    protected final static int MIN_WIDTH = 320;
    protected final static int MIN_HEIGHT = 240;
    protected static int shotCounter = 1;
    protected JLabel statusBar = null;
    protected JPanel visualContainer = null;
    protected Component visualComponent = null;
    protected JToolBar toolbar = null;
    protected MyToolBarAction formatButton = null;
    protected MyToolBarAction captureButton = null;
    protected Player player = null;
    protected CaptureDeviceInfo webCamDeviceInfo = null;
    protected MediaLocator ml = null;
    protected Dimension imageSize = null;
    protected FormatControl formatControl = null;
    protected VideoFormat currentFormat = null;
    protected Format[] videoFormats = null;
    protected MyVideoFormat[] myFormatList = null;
    protected boolean initialised = false;
    * Constructor
    public JWebCam ( String frameTitle )
    super ( frameTitle );
    try
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    catch ( Exception cnfe )
    System.out.println ("Note : Cannot load look and feel settings");
    setSize ( 320, 260 ); // default size...
    addWindowListener ( this );
    addComponentListener ( this );
    getContentPane().setLayout ( new BorderLayout() );
    visualContainer = new JPanel();
    visualContainer.setLayout ( new BorderLayout() );
    getContentPane().add ( visualContainer, BorderLayout.CENTER );
    statusBar = new JLabel ("");
    statusBar.setBorder ( new EtchedBorder() );
    getContentPane().add ( statusBar, BorderLayout.SOUTH );
    * Initialise
    * @returns true if web cam is detected
    public boolean initialise ( )
    throws Exception
    return ( initialise ( autoDetect() ) );
    * Initialise
    * @params _deviceInfo, specific web cam device if not autodetected
    * @returns true if web cam is detected
    public boolean initialise ( CaptureDeviceInfo _deviceInfo )
    throws Exception
    statusBar.setText ( "Initialising...");
    webCamDeviceInfo = _deviceInfo;
    if ( webCamDeviceInfo != null )
    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
    try
    setUpToolBar();
    getContentPane().add ( toolbar, BorderLayout.NORTH );
    ml = webCamDeviceInfo.getLocator();
    if ( ml != null )
    player = Manager.createRealizedPlayer ( ml );
    if ( player != null )
    player.start();
    formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
    videoFormats = webCamDeviceInfo.getFormats();
    visualComponent = player.getVisualComponent();
    if ( visualComponent != null )
    visualContainer.add ( visualComponent, BorderLayout.CENTER );
    myFormatList = new MyVideoFormat[videoFormats.length];
    for ( int i=0; i<videoFormats.length; i++ )
    myFormatList = new MyVideoFormat ( (VideoFormat)videoFormats );
    Format currFormat = formatControl.getFormat();
    if ( currFormat instanceof VideoFormat )
    currentFormat = (VideoFormat)currFormat;
    imageSize = currentFormat.getSize();
    visualContainer.setPreferredSize ( imageSize );
    setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
    else
    System.err.println ("Error : Cannot get current video format");
    invalidate();
    pack();
    return ( true );
    else
    System.err.println ("Error : Could not get visual component");
    return ( false );
    else
    System.err.println ("Error : Cannot create player");
    statusBar.setText ( "Cannot create player" );
    return ( false );
    else
    System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
    statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
    return ( false );
    catch ( IOException ioEx )
    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
    return ( false );
    catch ( NoPlayerException npex )
    statusBar.setText ("Cannot create player");
    return ( false );
    catch ( CannotRealizeException nre )
    statusBar.setText ( "Cannot realize player");
    return ( false );
    else
    return ( false );
    * Dynamically create menu items
    * @returns the device info object if found, null otherwise
    public void setFormat ( VideoFormat selectedFormat )
    if ( formatControl != null )
    player.stop();
    imageSize = selectedFormat.getSize();
    formatControl.setFormat ( selectedFormat );
    player.start();
    statusBar.setText ( "Format : " + selectedFormat );
    currentFormat = selectedFormat;
    visualContainer.setPreferredSize ( currentFormat.getSize() );
    setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
    else
    System.out.println ("Visual component not an instance of FormatControl");
    statusBar.setText ( "Visual component cannot change format" );
    public VideoFormat getFormat ( )
    return ( currentFormat );
    protected void setUpToolBar ( )
    toolbar = new JToolBar();
    // Note : If you supply the 16 x 16 bitmaps then you can replace
    // the commented line in the MyToolBarAction constructor
    formatButton = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
    captureButton = new MyToolBarAction ( "Capture", "BtnCapture.jpg" );
    toolbar.add ( formatButton );
    toolbar.add ( captureButton );
    getContentPane().add ( toolbar, BorderLayout.NORTH );
    protected void toolbarHandler ( MyToolBarAction actionBtn )
    if ( actionBtn == formatButton )
    Object selected = JOptionPane.showInputDialog (this,
    "Select Video format",
    "Capture format selection",
    JOptionPane.INFORMATION_MESSAGE,
    null, // Icon icon,
    myFormatList, // videoFormats,
    currentFormat );
    if ( selected != null )
    setFormat ( ((MyVideoFormat)selected).format );
    else if ( actionBtn == captureButton )
    Image photo = grabFrameImage ( );
    if ( photo != null )
    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
    else
    System.err.println ("Error : Could not grab frame");
    * autoDetects the first web camera in the system
    * searches for video for windows ( vfw ) capture devices
    * @returns the device info object if found, null otherwise
    public CaptureDeviceInfo autoDetect ( )
    Vector list = CaptureDeviceManager.getDeviceList ( null );
    CaptureDeviceInfo devInfo = null;
    if ( list != null )
    String name;
    for ( int i=0; i<list.size(); i++ )
    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
    name = devInfo.getName();
    if ( name.startsWith ("vfw:") )
    break;
    if ( devInfo != null && devInfo.getName().startsWith("vfw:") )
    return ( devInfo );
    else
    for ( int i = 0; i < 10; i++ )
    try
    name = VFWCapture.capGetDriverDescriptionName ( i );
    if (name != null && name.length() > 1)
    devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
    if ( devInfo != null )
    return ( devInfo );
    catch ( Exception ioEx )
    // ignore errors detecting device
    statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
    return ( null );
    else
    return ( null );
    * deviceInfo
    * @note outputs text information
    public void deviceInfo ( )
    if ( webCamDeviceInfo != null )
    Format[] formats = webCamDeviceInfo.getFormats();
    if ( ( formats != null ) && ( formats.length > 0 ) )
    for ( int i=0; i<formats.length; i++ )
    Format[] aFormat = formats;
    if ( aFormat[i] instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats.getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame() );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) { }
    public void windowClosed ( WindowEvent e ) { }
    public void windowDeactivated ( WindowEvent e ) { }
    public void windowDeiconified ( WindowEvent e ) { }
    public void windowIconified ( WindowEvent e ) { }
    public void windowOpened ( WindowEvent e ) { }
    public void componentHidden(ComponentEvent e) { }
    public void componentMoved(ComponentEvent e) { }
    public void componentShown(ComponentEvent e) { }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat _format )
    format = _format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MySnapshot extends JFrame
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "TimeSlice Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();
    when I run it I get the following errors
    BufferToImage cannot convert buffer
    could not grab frame
    pls help

    Do you expect anyone to read this?
    http://forum.java.sun.com/help.jspa?sec=formatting
    By the way, you have a condition that makes it print those messages. Check why that condiiton isn't rue.

  • EntityManager problem (nullPointer exception)

    Hello,
    I need help.
    I have created Entity from Table (table Users) from MySQL database.
    I'm using JPA.
    @Entity
    @NamedQueries( { @NamedQuery(name = "Users.findAll", query = "select o from Users o"),
                     @NamedQuery(name = "Users.findByUsername", query = "SELECT o FROM Users o WHERE o.username = :username")})
    @Table(name = "\"users\"")
    public class Users implements Serializable {
        @SuppressWarnings("compatibility:-1756790181151554415")
        private static final long serialVersionUID = 1L;
        @Column(name = "address", nullable = false)
        private String address;
        @Column(name = "city", nullable = false)
        private String city;
        @Column(name = "email", nullable = false)
        private String email;
        @Column(name = "firstPassword", nullable = false)
        private String firstPassword;
        @Column(name = "firstname", nullable = false)
        private String firstname;
        @Column(name = "lastname", nullable = false)
        private String lastname;
        @Column(name = "rank", nullable = false)
        private int rank;
        @Temporal(TemporalType.DATE)
        @Column(name = "regdate", nullable = false)
        private Date regdate;
        @Id
        @Column(name = "user_id", nullable = false)
        private long user_id;
        @Column(name = "username", nullable = false)
        private String username;
        public Users() {
        public Users(String address, String city, String email, String firstPassword, String firstname, String lastname,
                     int rank, Date regdate, long user_id, String username) {
            this.address = address;
            this.city = city;
            this.email = email;
            this.firstPassword = firstPassword;
            this.firstname = firstname;
            this.lastname = lastname;
            this.rank = rank;
            this.regdate = regdate;
            this.user_id = user_id;
            this.username = username;
        public String getAddress() {
            return address;
        public void setAddress(String address) {
            this.address = address;
        public String getCity() {
            return city;
        public void setCity(String city) {
            this.city = city;
        public String getEmail() {
            return email;
        public void setEmail(String email) {
            this.email = email;
        public String getFirstPassword() {
            return firstPassword;
        public void setFirstPassword(String firstPassword) {
            this.firstPassword = firstPassword;
        public String getFirstname() {
            return firstname;
        public void setFirstname(String firstname) {
            this.firstname = firstname;
        public String getLastname() {
            return lastname;
        public void setLastname(String lastname) {
            this.lastname = lastname;
        public int getRank() {
            return rank;
        public void setRank(int rank) {
            this.rank = rank;
        public Date getRegdate() {
            return regdate;
        public void setRegdate(Date regdate) {
            this.regdate = regdate;
        public long getUser_id() {
            return user_id;
        public void setUser_id(long user_id) {
            this.user_id = user_id;
        public String getUsername() {
            return username;
        public void setUsername(String username) {
            this.username = username;
    }and I have created ManagedBean LoginUser. In this class is method getUser().
            private Users getUser() {
                System.out.println("Username: " +username);
                try{
                    Users userr = (Users) entManager.createNamedQuery("Users.findByUsername").setParameter("username", username).getSingleResult();
                    loginUser.user = userr;
                    System.out.println("USER---- " +userr);
                    return userr;
                }catch(NoResultException nre){
                    System.out.println(nre.getMessage());
                    return null;
            }I have problem with entity manager because this row: Users userr = (Users) entManager.createNamedQuery("Users.findByUsername").setParameter("username", username).getSingleResult();* causes exception:
    Caused by: java.lang.NullPointerException
         at view.loginUser.getUser(loginUser.java:74)
            .I don't know why. This code is from my previous project from netbeans and there wasn't a problem.
    I don't see a problem.
    Can you help me ?
    Sorry for my English.
    Thanks.

    Does the persistence.xml define the persistence-unit ViewController? What is the persistence provider? Hibernate or Eclipselink? Is a datasource with MySQL deifned?
    With the EclipseLink provider the persistence.xml should be similar to the following.
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.0"
         xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
    http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
         <persistence-unit name="ViewController" transaction-type="JTA">
              <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
              <jta-data-source>java:jboss/datasources/MySQLDS</jta-data-source>
              <class>packagename.Users</class>
              <properties>
                   <property name="eclipselink.target-server" value="WebLogic_10"/>
                   <property name="eclipselink.target-database" value="MySQL"/>
                   <property name="eclipselink.ddl-generation" value="create-tables"/>
                   <property name="eclipselink.logging.level" value="FINEST"/>
                   <property name="eclipselink.dialect" value="org.hibernate.dialect.MySQLDialect" />
              </properties>
         </persistence-unit>
    </persistence>
    Edited by: dvohra16 on Feb 25, 2013 9:36 AM

  • JMFproblem in adding a layer over e palyer

    Hi to all.
    I'm a newbie to JMF.
    What I'm trying to do with no success is to add a LayeredPanel the visualComponent of the player
    and afterwards a simpel JLabel.
    It must be for the fact that teh visualcomponents contains the component given from the layer whitch must be a thread (but I'm not sure)
    I'm really desperate beacause I can't find a way out.
    For whom has already worked with JMF it sould be easy but not for my.
    Any hint or help Would be really wonderful
    Thanks to all in advance
    Mandy
    I Post here my code
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import com.sun.media.protocol.vfw.VFWCapture;
    public class MediaPlayer extends JFrame implements WindowListener,
    ComponentListener {
         private MenuBar mb;
         private Menu fileMenu;
         private Menu aboutMenu;
         private MenuItem aboutItem;
         private MenuItem exitItem;
         protected final static int MIN_WIDTH = 320;
         protected final static int MIN_HEIGHT = 240;
         protected static int shotCounter = 1;
         protected JLabel statusBar = null;
         protected JLayeredPane visualContainer = null;
         protected Component visualComponent = null;
         protected Player player = null;
         protected CaptureDeviceInfo webCamDeviceInfo = null;
         protected MediaLocator ml = null;
         protected Dimension imageSize = null;
         protected FormatControl formatControl = null;
         protected VideoFormat currentFormat = null;
         protected Format[] videoFormats = null;
         protected boolean initialised = false;
          * Costruttore *
         public MediaPlayer(String frameTitle) {
              super(frameTitle);
    //          dimensione della finestra
              Image icon = Toolkit.getDefaultToolkit().getImage("icona.gif");
              this.setIconImage(icon);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              this.setLocation(10 , 10);
              this.setSize(screenSize.width-100,screenSize.height-100);
              this.setResizable(false);
    // Add Menu Bar
              mb = new MenuBar();
              fileMenu = new Menu("File");
              mb.add(fileMenu);
              setMenuBar(mb);
              aboutMenu = new Menu("About");
              fileMenu.add(aboutMenu);
              AboutAction aboutAction = new AboutAction();
              aboutItem = new MenuItem("Application");
              aboutItem.addActionListener(aboutAction);
              aboutMenu.add(aboutItem);
              ExitAction action2 = new ExitAction();
              exitItem = new MenuItem("Exit");
              exitItem.addActionListener(action2);
              fileMenu.add(exitItem);
              addWindowListener(this);
              addComponentListener(this);
              getContentPane().setLayout(new BorderLayout());
              JPanel genericcontainer = new JPanel();
              //visualContainer = new JLayeredPane();
              //visualContainer.setLayout(new BorderLayout());
              visualContainer = new JLayeredPane();
              visualContainer.setBorder(BorderFactory.createTitledBorder(
                                        "STREAM VIEWER"));
              genericcontainer.add(visualContainer);
              getContentPane().add(genericcontainer, BorderLayout.CENTER);
              statusBar = new JLabel("");
              statusBar.setBorder(new EtchedBorder());
              getContentPane().add(statusBar, BorderLayout.SOUTH);
          * @restituisce true se viene trovata una webcam *
         public boolean initialise() throws Exception {
              return (initialise(autoDetect()));
          * @params _deviceInfo, informazioni sulla webcam rilevata * @restituisce
          * true se la webcam viene correttamente rilevata*
         public boolean initialise(CaptureDeviceInfo _deviceInfo) throws Exception {
              statusBar.setText("detecting WEBCAM");
              webCamDeviceInfo = _deviceInfo;
              if (webCamDeviceInfo != null) {
                   statusBar.setText("Connessione alla webcam : "
                             + webCamDeviceInfo.getName());
                   try {
                        ml = webCamDeviceInfo.getLocator();
                        if (ml != null) {
                             player = Manager.createRealizedPlayer(ml);
                             if (player != null) {
                                  player.start();
                                  formatControl = (FormatControl) player
                                  .getControl("javax.media.control.FormatControl");
                                  videoFormats = webCamDeviceInfo.getFormats();
                                  visualComponent = player.getVisualComponent();
                                  if (visualComponent != null) {
                                       visualContainer.setOpaque(false);
                                       visualContainer.add(visualComponent, new Integer(1));
                                       visualContainer.add(new JLabel("sssss"), new Integer(2));
                                       Format currFormat = formatControl.getFormat();
                                       if (currFormat instanceof VideoFormat) {
                                            currentFormat = (VideoFormat) currFormat;
                                            imageSize = currentFormat.getSize();
                                            visualContainer.setPreferredSize(imageSize);
                                            setSize(this.getSize().width, this.getSize().height
                                                      + statusBar.getHeight());
                                       } else {
                                            System.err
                                            .println("Errore nella rilevazione del formato video.");
                                       invalidate();
                                       pack();
                                       return (true);
                                  } else {
                                       System.err
                                       .println("Errore nella creazione della componente visiva.");
                                       return (false);
                             } else {
                                  System.err
                                  .println("Errore nella creazione del player.");
                                  statusBar.setText("Errore nella creazione del player.");
                                  return (false);
                        } else {
                             System.err.println("Nessun MediaLocator per: "
                                       + webCamDeviceInfo.getName());
                             statusBar.setText("Nessun MediaLocator per: "
                                       + webCamDeviceInfo.getName());
                             return (false);
                   } catch (IOException ioEx) {
                        statusBar.setText("Connessione a: "
                                  + webCamDeviceInfo.getName());
                        return (false);
                   } catch (NoPlayerException npex) {
                        statusBar.setText("Errore nella creazione del player.");
                        return (false);
                   } catch (CannotRealizeException nre) {
                        statusBar.setText("Errore nella realizzazione del player.");
                        return (false);
              } else {
                   return (false);
          * Cerca una webcam installata per Windows (vfw)*
          * @restituisce le informazioni sul device trovato
         public CaptureDeviceInfo autoDetect() {
              Vector list = CaptureDeviceManager.getDeviceList(null);
              CaptureDeviceInfo devInfo = null;
              if (list != null) {
                   String name;
                   for (int i = 0; i < list.size(); i++) {
                        devInfo = (CaptureDeviceInfo) list.elementAt(i);
                        name = devInfo.getName();
                        if (name.startsWith("vfw:")) {
                             break;
                   if (devInfo != null && devInfo.getName().startsWith("vfw:")) {
                        return (devInfo);
                   } else {
                        for (int i = 0; i < 10; i++) {
                             try {
                                  name = VFWCapture.capGetDriverDescriptionName(i);
                                  if (name != null && name.length() > 1) {
                                       devInfo = com.sun.media.protocol.vfw.VFWSourceStream
                                       .autoDetect(i);
                                       if (devInfo != null) {
                                            return (devInfo);
                             } catch (Exception ioEx) {
                                  statusBar
                                  .setText("Errore nella ricerca della webcam : "
                                            + ioEx.getMessage());
                        return (null);
              } else {
                   return (null);
         public void playerClose() {
              if (player != null) {
                   player.close();
                   player.deallocate();
                   player = null;
         public void windowClosing(WindowEvent e) {
              playerClose();
              System.exit(1);
         public void componentResized(ComponentEvent e) {
              Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
              setSize(dim.width-100,dim.height-100);
         public void windowActivated(WindowEvent e) {
         public void windowClosed(WindowEvent e) {
         public void windowDeactivated(WindowEvent e) {
         public void windowDeiconified(WindowEvent e) {
         public void windowIconified(WindowEvent e) {
         public void windowOpened(WindowEvent e) {
         public void componentHidden(ComponentEvent e) {
         public void componentMoved(ComponentEvent e) {
         public void componentShown(ComponentEvent e) {
         protected void finalize() throws Throwable {
              playerClose();
              super.finalize();
         public class ExitAction implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   playerClose();
                   System.exit(1);
         public class AboutAction implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   JFrame myframe = new JFrame();
                  JOptionPane optionPane = new JOptionPane("\n" +
                            "   Java Application\n" +
                            "\n" +
                            "Created by M.Zachariadou\n" +
                            "\n" +
                            " uses jre 1.6.0_3\n and JMF 2.1.1" +
                            "\n" +
                         JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION);
                     optionPane.createDialog(myframe, null).setVisible(true);
         public static void main(String[] args) {
              try {
                   MediaPlayer myWebCam = new MediaPlayer("Video Streaming from WEBCAM detected");
                   myWebCam.setVisible(true);
                   if (!myWebCam.initialise()) {
                        System.out.println("WebCam non trovata / inizializzata");
              } catch (Exception ex) {
                   ex.printStackTrace();
    }

    After Effects will mix and match any size and pixel aspect ratio footage without problems as long as you have all footage items interpreted properly. It would help us a lot if we knew more about your composition. You should always use the presets for comp size and you should never change the PAR that a preset gives you. Distortion in non square standard comps is removed when you select PAR correction in preview.
    If you don't understand any of what I'm talking about then you must read and understand the help materials on rendering, composition setings and pixel aspect ratios. To keep your life simple always work with a square pixel preset then render using a pre-set for your desired delivery method.

  • Updated : No question, just example web cam capture code

    Hi,
    I posted this example a while back, but it had some cosmetic bugs in it.
    Here's an updated version.
    Quick Start
    1. Install JMF 2.1.1e (performance pack version)
    ( see imports list in source code if you really want to run it using the older version 2.1.1c )
    2. You have to set the JMF_HOME or JMFHOME environment variable. Can't remember which one.
    "Nearly sure" it's JMF_HOME.
    3. Connect your camera
    4. run jmfinit ( may need to do a few times until it detects your camera )
    When it does, you're in business, and you can try to run the code
    5. Run java -cp .;%JMF_HOME%\lib\jmf.jar JWebCam
    known issue
    Under Java 1.5 / 5 - When capturing a frame, and then resizing that snapshots JFrame, the image did not always scale up and display.
    That does work under Java 1.3.1_06 .
    Tested on Win98 2nd edition, Java 1.3.1_06, and Creative Web Cam Pro.
    Legal stuff in plain english : This code is available for use by everyone, personal or commercial, no need to mention me in licenses or anything. It's just a demo I knocked up for myself. So I am under no obligation to support this. Use it at your own risk.... that implies you can't blame or sue me for anything that goes wrong.
    If you like the code, I'd be happy to hear whereabouts you are in the world :-)
    Also note : this is the limits of my JMF experience at present.
    If you've a separate question, post it to a new topic!
    regards,
    Owen ( Dublin, Ireland )
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture;         // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture;   // JMF 2.1.1e version
    public class JWebCam extends JFrame
        implements WindowListener,  ComponentListener
        protected final static int MIN_WIDTH  = 100;  // 320;
        protected final static int MIN_HEIGHT = 100;  // 240;
        protected static int shotCounter = 1;
        protected JLabel statusBar = null;
        protected JPanel visualContainer = null;
        protected Component visualComponent = null;
        protected JToolBar toolbar = null;
        protected MyToolBarAction formatButton    = null;
        protected MyToolBarAction captureButton   = null;
        protected Player player = null;
        protected CaptureDeviceInfo webCamDeviceInfo = null;
        protected MediaLocator ml = null;
        protected Dimension imageSize = null;
        protected FormatControl formatControl = null;
        protected VideoFormat currentFormat = null;
        protected Format[] videoFormats = null;
        protected MyVideoFormat[] myFormatList = null;
        protected MyCaptureDeviceInfo[] myCaptureDevices = null;
        protected boolean initialised = false;
         * Constructor
        public JWebCam ( String frameTitle )
            super ( frameTitle );
            try
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            catch ( Exception cnfe )
                System.out.println ("Note : Cannot load look and feel settings");
            setSize ( 320, 260 ); // default size...
            addWindowListener ( this );
            addComponentListener ( this );
            getContentPane().setLayout ( new BorderLayout() );
            visualContainer = new JPanel();
            visualContainer.setLayout ( new BorderLayout() );
            getContentPane().add ( visualContainer, BorderLayout.CENTER );
            statusBar = new JLabel ("")
                // Nasty bug workaround
                // The minimum JLabel size was determined by the text in the status bar
                // So the layoutmanager wouldn't shrink the window for the video image
                public Dimension getPreferredSize (  )
                    // get the JLabel to "allow" a minimum of 10 pixels width
                    // not to work out the minimum size from the text length
                    return ( new Dimension ( 10, super.getPreferredSize().height ) );
            statusBar.setBorder ( new EtchedBorder() );
            getContentPane().add ( statusBar, BorderLayout.SOUTH );
         * Initialise
         * @returns true if web cam is detected
        public boolean initialise ( )
            throws Exception
            MyCaptureDeviceInfo[] cams = autoDetect();
            if ( cams.length > 0 )
                if ( cams.length == 1 )
                     System.out.println ("Note : 1 web cam detected");
                     return ( initialise ( cams[0].capDevInfo ) );
                else
                    System.out.println ("Note : " + cams.length + " web cams detected");
                    Object selected = JOptionPane.showInputDialog (this,
                                                                   "Select Video format",
                                                                   "Capture format selection",
                                                                   JOptionPane.INFORMATION_MESSAGE,
                                                                   null,        //  Icon icon,
                                                                   cams, // videoFormats,
                                                                   cams[0] );
                    if ( selected != null )
                        return ( initialise ( ((MyCaptureDeviceInfo)selected).capDevInfo ) );
                    else
                        return ( initialise ( null ) );
            else
                return ( initialise ( null ) );
         * Initialise
         * @params _deviceInfo, specific web cam device if not autodetected
         * @returns true if web cam is detected
        public boolean initialise ( CaptureDeviceInfo _deviceInfo )
            throws Exception
            statusBar.setText ( "Initialising...");
            webCamDeviceInfo = _deviceInfo;
            if ( webCamDeviceInfo != null )
                statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                try
                    setUpToolBar();
                    getContentPane().add ( toolbar, BorderLayout.NORTH );
                    ml = webCamDeviceInfo.getLocator();
                    if ( ml != null )
                        player = Manager.createRealizedPlayer ( ml );
                        if ( player != null )
                            player.start();
                            formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                            videoFormats = webCamDeviceInfo.getFormats();
                            myFormatList = new MyVideoFormat[videoFormats.length];
                            for ( int i=0; i<videoFormats.length; i++ )
                                myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                            Format currFormat = formatControl.getFormat();
                            visualComponent = player.getVisualComponent();
                            if ( visualComponent != null )
                                visualContainer.add ( visualComponent, BorderLayout.CENTER );
                                if ( currFormat instanceof VideoFormat )
                                     currentFormat = (VideoFormat)currFormat;
                                     imageSize = currentFormat.getSize();
                                     visualContainer.setPreferredSize ( imageSize );
                                     setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                                else
                                    System.err.println ("Error : Cannot get current video format");
                                invalidate();
                                pack();
                                return ( true );
                            else
                                System.err.println ("Error : Could not get visual component");
                                return ( false );
                        else
                            System.err.println ("Error : Cannot create player");
                            statusBar.setText ( "Cannot create player" );
                            return ( false );
                    else
                        System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
                        statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                        return ( false );
                catch ( IOException ioEx )
                    System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                    return ( false );
                catch ( NoPlayerException npex )
                    statusBar.setText ("Cannot create player");
                    return ( false );
                catch ( CannotRealizeException nre )
                    statusBar.setText ( "Cannot realize player");
                    return ( false );
            else
                return ( false );
         * Dynamically create menu items
         * @returns the device info object if found, null otherwise
        public void setFormat ( VideoFormat selectedFormat )
            if ( formatControl != null )
                // player.stop();       // not needed and big performance hit
                currentFormat = selectedFormat;
                if ( visualComponent != null )
                     visualContainer.remove ( visualComponent );
                imageSize = currentFormat.getSize();
                visualContainer.setPreferredSize ( imageSize );
                statusBar.setText ( "Format : " + currentFormat );
                System.out.println ("Format : " + currentFormat );
                formatControl.setFormat ( currentFormat );
                // player.start();  // not needed and big performance hit
                visualComponent = player.getVisualComponent();
                if ( visualComponent != null )
                    visualContainer.add ( visualComponent, BorderLayout.CENTER );
                invalidate();       // let the layout manager work out the sizes
                pack();
            else
                System.out.println ("Visual component not an instance of FormatControl");
                statusBar.setText ( "Visual component cannot change format" );
        public VideoFormat getFormat ( )
            return ( currentFormat );
        protected void setUpToolBar ( )
            toolbar = new JToolBar();
            // Note : due to cosmetic glitches when undocking and docking the toolbar,
            //        I've set this to false.
            toolbar.setFloatable(false);
            // Note : If you supply the 16 x 16 bitmaps then you can replace
            // the commented line in the MyToolBarAction constructor
            formatButton    = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
            captureButton   = new MyToolBarAction ( "Capture",    "BtnCapture.jpg" );
            toolbar.add ( formatButton );
            toolbar.add ( captureButton );
            getContentPane().add ( toolbar, BorderLayout.NORTH );
        protected void toolbarHandler ( MyToolBarAction actionBtn )
            if ( actionBtn == formatButton )
                Object selected = JOptionPane.showInputDialog (this,
                                                               "Select Video format",
                                                               "Capture format selection",
                                                               JOptionPane.INFORMATION_MESSAGE,
                                                               null,        //  Icon icon,
                                                               myFormatList, // videoFormats,
                                                               currentFormat );
                if ( selected != null )
                    setFormat ( ((MyVideoFormat)selected).format );
            else if ( actionBtn == captureButton )
                Image photo = grabFrameImage ( );
                if ( photo != null )
                    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
                else
                    System.err.println ("Error : Could not grab frame");
         * autoDetects the first web camera in the system
         * searches for video for windows ( vfw ) capture devices
         * @returns the device info object if found, null otherwise
        public MyCaptureDeviceInfo[] autoDetect ( )
            Vector list = CaptureDeviceManager.getDeviceList ( null );
            CaptureDeviceInfo devInfo = null;
            String name;
            Vector capDevices = new Vector();
            if ( list != null )
                for ( int i=0; i<list.size(); i++ )
                    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                    name = devInfo.getName();
                    if ( name.startsWith ("vfw:") )
                        System.out.println ("DeviceManager List : " + name );
                        capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
            else
                for ( int i = 0; i < 10; i++ )
                    try
                        name = VFWCapture.capGetDriverDescriptionName ( i );
                        if (name != null && name.length() > 1)
                            devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                            if ( devInfo != null )
                                System.out.println ("VFW Autodetect List : " + name );
                                capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
                    catch ( Exception ioEx )
                        System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                        // ignore errors detecting device
                        statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
            MyCaptureDeviceInfo[] detected = new MyCaptureDeviceInfo[ capDevices.size() ];
            for ( int i=0; i<capDevices.size(); i++ )
                detected[i] = (MyCaptureDeviceInfo)capDevices.elementAt ( i );
            return ( detected );
         * deviceInfo
         * @note outputs text information
        public void deviceInfo ( )
            if ( webCamDeviceInfo != null )
                Format[] formats = webCamDeviceInfo.getFormats();
                if ( ( formats != null ) && ( formats.length > 0 ) )
                for ( int i=0; i<formats.length; i++ )
                    Format aFormat = formats;
    if ( aFormat instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame() );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) {   }
    public void windowClosed ( WindowEvent e ) {   }
    public void windowDeactivated ( WindowEvent e ) {   }
    public void windowDeiconified ( WindowEvent e ) {   }
    public void windowIconified ( WindowEvent e ) {   }
    public void windowOpened ( WindowEvent e ) {   }
    public void componentHidden(ComponentEvent e) {   }
    public void componentMoved(ComponentEvent e) {   }
    public void componentShown(ComponentEvent e) {   }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat format )
    this.format = format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MyCaptureDeviceInfo
    public CaptureDeviceInfo capDevInfo;
    public MyCaptureDeviceInfo ( CaptureDeviceInfo devInfo )
    capDevInfo = devInfo;
    public String toString ( )
    return ( capDevInfo.getName() );
    class MySnapshot extends JFrame implements ImageObserver
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    super.paint ( g );
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), Color.black, this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();

    Hi,
    Here's a working version.
    If there are no spaces after the "<" symbol, it thinks it's a HTML tag.
    Putting spaces in, stops this.
    cheers,
    Owen
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture;         // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture;   // JMF 2.1.1e version
    public class JWebCam extends JFrame
        implements WindowListener,  ComponentListener
        protected final static int MIN_WIDTH  = 100;  // 320;
        protected final static int MIN_HEIGHT = 100;  // 240;
        protected static int shotCounter = 1;
        protected JLabel statusBar = null;
        protected JPanel visualContainer = null;
        protected Component visualComponent = null;
        protected JToolBar toolbar = null;
        protected MyToolBarAction formatButton    = null;
        protected MyToolBarAction captureButton   = null;
        protected Player player = null;
        protected CaptureDeviceInfo webCamDeviceInfo = null;
        protected MediaLocator ml = null;
        protected Dimension imageSize = null;
        protected FormatControl formatControl = null;
        protected VideoFormat currentFormat = null;
        protected Format[] videoFormats = null;
        protected MyVideoFormat[] myFormatList = null;
        protected MyCaptureDeviceInfo[] myCaptureDevices = null;
        protected boolean initialised = false;
         * Constructor
        public JWebCam ( String frameTitle )
            super ( frameTitle );
            try
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            catch ( Exception cnfe )
                System.out.println ("Note : Cannot load look and feel settings");
            setSize ( 320, 260 ); // default size...
            addWindowListener ( this );
            addComponentListener ( this );
            getContentPane().setLayout ( new BorderLayout() );
            visualContainer = new JPanel();
            visualContainer.setLayout ( new BorderLayout() );
            getContentPane().add ( visualContainer, BorderLayout.CENTER );
            statusBar = new JLabel ("")
                // Nasty bug workaround
                // The minimum JLabel size was determined by the text in the status bar
                // So the layoutmanager wouldn't shrink the window for the video image
                public Dimension getPreferredSize (  )
                    // get the JLabel to "allow" a minimum of 10 pixels width
                    // not to work out the minimum size from the text length
                    return ( new Dimension ( 10, super.getPreferredSize().height ) );
            statusBar.setBorder ( new EtchedBorder() );
            getContentPane().add ( statusBar, BorderLayout.SOUTH );
         * Initialise
         * @returns true if web cam is detected
        public boolean initialise ( )
            throws Exception
            MyCaptureDeviceInfo[] cams = autoDetect();
            if ( cams.length > 0 )
                if ( cams.length == 1 )
                     System.out.println ("Note : 1 web cam detected");
                     return ( initialise ( cams[0].capDevInfo ) );
                else
                    System.out.println ("Note : " + cams.length + " web cams detected");
                    Object selected = JOptionPane.showInputDialog (this,
                                                                   "Select Video format",
                                                                   "Capture format selection",
                                                                   JOptionPane.INFORMATION_MESSAGE,
                                                                   null,        //  Icon icon,
                                                                   cams, // videoFormats,
                                                                   cams[0] );
                    if ( selected != null )
                        return ( initialise ( ((MyCaptureDeviceInfo)selected).capDevInfo ) );
                    else
                        return ( initialise ( null ) );
            else
                return ( initialise ( null ) );
         * Initialise
         * @params _deviceInfo, specific web cam device if not autodetected
         * @returns true if web cam is detected
        public boolean initialise ( CaptureDeviceInfo _deviceInfo )
            throws Exception
            statusBar.setText ( "Initialising...");
            webCamDeviceInfo = _deviceInfo;
            if ( webCamDeviceInfo != null )
                statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                try
                    setUpToolBar();
                    getContentPane().add ( toolbar, BorderLayout.NORTH );
                    ml = webCamDeviceInfo.getLocator();
                    if ( ml != null )
                        player = Manager.createRealizedPlayer ( ml );
                        if ( player != null )
                            player.start();
                            formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                            videoFormats = webCamDeviceInfo.getFormats();
                            myFormatList = new MyVideoFormat[videoFormats.length];
                            for ( int i=0; i < videoFormats.length; i++ )
                                myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                            Format currFormat = formatControl.getFormat();
                            visualComponent = player.getVisualComponent();
                            if ( visualComponent != null )
                                visualContainer.add ( visualComponent, BorderLayout.CENTER );
                                if ( currFormat instanceof VideoFormat )
                                     currentFormat = (VideoFormat)currFormat;
                                     imageSize = currentFormat.getSize();
                                     visualContainer.setPreferredSize ( imageSize );
                                     setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                                else
                                    System.err.println ("Error : Cannot get current video format");
                                invalidate();
                                pack();
                                return ( true );
                            else
                                System.err.println ("Error : Could not get visual component");
                                return ( false );
                        else
                            System.err.println ("Error : Cannot create player");
                            statusBar.setText ( "Cannot create player" );
                            return ( false );
                    else
                        System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
                        statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                        return ( false );
                catch ( IOException ioEx )
                    System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                    return ( false );
                catch ( NoPlayerException npex )
                    statusBar.setText ("Cannot create player");
                    return ( false );
                catch ( CannotRealizeException nre )
                    statusBar.setText ( "Cannot realize player");
                    return ( false );
            else
                return ( false );
         * Dynamically create menu items
         * @returns the device info object if found, null otherwise
        public void setFormat ( VideoFormat selectedFormat )
            if ( formatControl != null )
                player.stop();
                currentFormat = selectedFormat;
                if ( visualComponent != null )
                     visualContainer.remove ( visualComponent );
                imageSize = currentFormat.getSize();
                visualContainer.setPreferredSize ( imageSize );
                statusBar.setText ( "Format : " + currentFormat );
                System.out.println ("Format : " + currentFormat );
                formatControl.setFormat ( currentFormat );
                player.start();
                visualComponent = player.getVisualComponent();
                if ( visualComponent != null )
                    visualContainer.add ( visualComponent, BorderLayout.CENTER );
                invalidate();       // let the layout manager work out the sizes
                pack();
            else
                System.out.println ("Visual component not an instance of FormatControl");
                statusBar.setText ( "Visual component cannot change format" );
        public VideoFormat getFormat ( )
            return ( currentFormat );
        protected void setUpToolBar ( )
            toolbar = new JToolBar();
            // Note : due to cosmetic glitches when undocking and docking the toolbar,
            //        I've set this to false.
            toolbar.setFloatable(false);
            // Note : If you supply the 16 x 16 bitmaps then you can replace
            // the commented line in the MyToolBarAction constructor
            formatButton    = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
            captureButton   = new MyToolBarAction ( "Capture",    "BtnCapture.jpg" );
            toolbar.add ( formatButton );
            toolbar.add ( captureButton );
            getContentPane().add ( toolbar, BorderLayout.NORTH );
        protected void toolbarHandler ( MyToolBarAction actionBtn )
            if ( actionBtn == formatButton )
                Object selected = JOptionPane.showInputDialog (this,
                                                               "Select Video format",
                                                               "Capture format selection",
                                                               JOptionPane.INFORMATION_MESSAGE,
                                                               null,        //  Icon icon,
                                                               myFormatList, // videoFormats,
                                                               currentFormat );
                if ( selected != null )
                    setFormat ( ((MyVideoFormat)selected).format );
            else if ( actionBtn == captureButton )
                Image photo = grabFrameImage ( );
                if ( photo != null )
                    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
                else
                    System.err.println ("Error : Could not grab frame");
         * autoDetects the first web camera in the system
         * searches for video for windows ( vfw ) capture devices
         * @returns the device info object if found, null otherwise
        public MyCaptureDeviceInfo[] autoDetect ( )
            Vector list = CaptureDeviceManager.getDeviceList ( null );
            CaptureDeviceInfo devInfo = null;
            String name;
            Vector capDevices = new Vector();
            if ( list != null )
                for ( int i=0; i < list.size(); i++ )
                    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                    name = devInfo.getName();
                    if ( name.startsWith ("vfw:") )
                        System.out.println ("DeviceManager List : " + name );
                        capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
            else
                for ( int i = 0; i < 10; i++ )
                    try
                        name = VFWCapture.capGetDriverDescriptionName ( i );
                        if (name != null && name.length() > 1)
                            devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                            if ( devInfo != null )
                                System.out.println ("VFW Autodetect List : " + name );
                                capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
                    catch ( Exception ioEx )
                        System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                        // ignore errors detecting device
                        statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
            MyCaptureDeviceInfo[] detected = new MyCaptureDeviceInfo[ capDevices.size() ];
            for ( int i=0; i < capDevices.size(); i++ )
                detected[i] = (MyCaptureDeviceInfo)capDevices.elementAt ( i );
            return ( detected );
         * deviceInfo
         * @note outputs text information
        public void deviceInfo ( )
            if ( webCamDeviceInfo != null )
                Format[] formats = webCamDeviceInfo.getFormats();
                if ( ( formats != null ) && ( formats.length > 0 ) )
                for ( int i=0; i < formats.length; i++ )
                    Format aFormat = formats;
    if ( aFormat instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame() );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) {   }
    public void windowClosed ( WindowEvent e ) {   }
    public void windowDeactivated ( WindowEvent e ) {   }
    public void windowDeiconified ( WindowEvent e ) {   }
    public void windowIconified ( WindowEvent e ) {   }
    public void windowOpened ( WindowEvent e ) {   }
    public void componentHidden(ComponentEvent e) {   }
    public void componentMoved(ComponentEvent e) {   }
    public void componentShown(ComponentEvent e) {   }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat format )
    this.format = format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MyCaptureDeviceInfo
    public CaptureDeviceInfo capDevInfo;
    public MyCaptureDeviceInfo ( CaptureDeviceInfo devInfo )
    capDevInfo = devInfo;
    public String toString ( )
    return ( capDevInfo.getName() );
    class MySnapshot extends JFrame implements ImageObserver
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    super.paint ( g );
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), Color.black, this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();

  • No Question, just example web cam capture code

    Hi,
    Since loads of people ask for an example of capturing pics from a web cam, here's one that captures pics, lets you take snapshots, which it displays in another frame. When you shut down the frame it asks if you want to save it to a JPEG.
    I'm mainly posting this to spite Eka_Kupkova, who only visits this forum to shamelessly advertise a commercial Twain based package in every single posting on this forum which mentions web cams.
    Notes : ( Could be more, read the install docs for JMF )
    1. you must download the "performance" version of jmf to capture video.
    2. I "think" you need to setup the JMF_HOME environment variable
    3. Run the jmfinit program to detect your camera and register it.
    I had to run it a couple of times before it worked.
    4. I had 2 icons for my toolbar, BtnFormat.jpg and BtnCapture.jpg.
    They were just 16 x 16 pixel bitmaps, you can make them up yourself.
    5. I assume you've got the webcam working and the driver installed already.
    Ps. if you find this useful, then reply back with where you are in the world. I'm in Dublin, Ireland.
    cheers,
    Owen
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // Ps. I think JMF 2.1.1c used a different package for this class..
    import com.sun.media.vfw.VFWCapture;
    public class JWebCam extends JFrame
                              implements WindowListener,
                                             ComponentListener
         protected final static int MIN_WIDTH  = 320;
         protected final static int MIN_HEIGHT = 240;
         protected static int shotCounter = 1;
         protected JLabel statusBar = null;
         protected Component visualComponent = null;
         protected JToolBar toolbar = null;
         protected MyToolBarAction formatButton  = null;
         protected MyToolBarAction captureButton = null;
        protected Player player = null;
        protected CaptureDeviceInfo webCamDeviceInfo = null;
        protected MediaLocator ml = null;
        protected Dimension imageSize = null;
        protected FormatControl formatControl = null;
        protected VideoFormat currentFormat = null;
        protected Format[] videoFormats = null;
        protected MyVideoFormat[] myFormatList = null;
          * Constructor
        public JWebCam ( String frameTitle )
             super ( frameTitle );
              try
                  UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
             catch ( Exception cnfe )
                  System.out.println ("Note : Cannot load look and feel settings");
             addWindowListener ( this );
             addComponentListener ( this );
             getContentPane().setLayout ( new BorderLayout() );
             statusBar = new JLabel ("Initialising...");
             statusBar.setBorder ( new EtchedBorder() );
             getContentPane().add ( statusBar, BorderLayout.SOUTH );
             setSize ( 320, 260 ); // default size...
             setVisible ( true );
          * Initialise
          * @returns true if web cam is detected
         public boolean initialise ( )
              throws Exception
              return ( initialise ( autoDetect() ) );
          * Initialise
          * @params _deviceInfo, specific web cam device if not autodetected
          * @returns true if web cam is detected
         public boolean initialise ( CaptureDeviceInfo _deviceInfo )
              throws Exception
              webCamDeviceInfo = _deviceInfo;
             if ( webCamDeviceInfo != null )
                  statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                  try
                        // setUpMenu ( );
                        setUpToolBar();
                        getContentPane().add ( toolbar, BorderLayout.NORTH );
                       ml = webCamDeviceInfo.getLocator();
                       if ( ml != null )
                          player = Manager.createRealizedPlayer ( ml );
                          if ( player != null )
                               formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                                    videoFormats = webCamDeviceInfo.getFormats();
                                    setFormat ( (VideoFormat)videoFormats[0] );
                               // player.start();
                                    visualComponent = player.getVisualComponent();
                                    getContentPane().add ( visualComponent, BorderLayout.CENTER );
                                    invalidate();
                                    pack();
                                    setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                                myFormatList = new MyVideoFormat[videoFormats.length];
                                for ( int i=0; i<videoFormats.length; i++ )
                                     myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                     else
                          statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                        return ( true );
                   catch ( IOException ioEx )
                       statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                        return ( false );
                   catch ( NoPlayerException npex )
                        statusBar.setText ("Cannot create player");
                        return ( false );
                   catch ( CannotRealizeException nre )
                        statusBar.setText ( "Cannot realize player");
                        return ( false );
             else
                  return ( false );
          * Dynamically create menu items
          * @returns the device info object if found, null otherwise
         public void setFormat ( VideoFormat selectedFormat )
              if ( formatControl != null )
                   player.stop();
                   statusBar.setText ( "Format : " + selectedFormat );
                   imageSize = selectedFormat.getSize();
                   formatControl.setFormat ( selectedFormat );
                   currentFormat = selectedFormat;
                   setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                   player.start();
              else
                   System.out.println ("Visual component not an instance of FormatControl");
                   statusBar.setText ( "Visual component cannot change format" );
         protected void setUpToolBar ( )
              toolbar = new JToolBar();
              formatButton  = new MyToolBarAction ( "Format",  "BtnFormat.jpg" );
              captureButton = new MyToolBarAction ( "Capture", "BtnCapture.jpg" );
              if ( formatButton != null )
                    toolbar.add ( formatButton );
              toolbar.add ( captureButton );
              getContentPane().add ( toolbar, BorderLayout.NORTH );
         protected void toolbarHandler ( MyToolBarAction actionBtn )
              if ( actionBtn == formatButton )
                      // JOptionPane.showConfirmDialog ( this, "Format Dialog" );
                      Object selected = JOptionPane.showInputDialog (this,
                                                                     "Select Video format",
                                                                     "Capture format selection",
                                                                     JOptionPane.INFORMATION_MESSAGE,
                                                                     null,          //     Icon icon,
                                                                     myFormatList, // videoFormats,
                                                                     currentFormat );
                   if ( selected != null )
                        setFormat ( ((MyVideoFormat)selected).format );
              else if ( actionBtn == captureButton )
                   Image photo = grabFrameImage ( );
                   MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
          * autoDetects the first web camera in the system
          * @returns the device info object if found, null otherwise
        public CaptureDeviceInfo autoDetect ( )
              Vector list = CaptureDeviceManager.getDeviceList ( null );
              CaptureDeviceInfo devInfo = null;
              if ( list != null )
                   String name;
                   for ( int i=0; i<list.size(); i++ )
                        devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                        name = devInfo.getName();
                      if ( name.startsWith ("vfw:") )
                            break;
                   if ( devInfo != null && devInfo.getName().startsWith("vfw:") )
                       return ( devInfo );
                   else
                      for ( int i = 0; i < 10; i++ )
                           try
                               name = VFWCapture.capGetDriverDescriptionName ( i );
                               if (name != null && name.length() > 1)
                                       devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                                       if ( devInfo != null )
                                            return ( devInfo );
                             catch ( Exception ioEx )
                                  // ignore errors detecting device
                                  statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
                       return ( null );
              else
                   return ( null );
          * deviceInfo
          * @note outputs text information
         public void deviceInfo ( )
             if ( webCamDeviceInfo != null )
                  Format[] formats = webCamDeviceInfo.getFormats();
                  if ( ( formats != null ) && ( formats.length > 0 ) )
                  for ( int i=0; i<formats.length; i++ )
                       Format aFormat = formats;
                   if ( aFormat instanceof VideoFormat )
                        Dimension dim = ((VideoFormat)aFormat).getSize();
                        System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
                   else
                        System.out.println ("Format " + i + " : " + formats[i].getEncoding() );
         else
              System.out.println ("Error : No web cam detected");
         * grabs a frame's buffer from the web cam / device
         * @returns A frames buffer
         public Buffer grabFrameBuffer ( )
              if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    Buffer buf = fgc.grabFrame();
    return ( buf );
    else
         return ( null );
         * grabs a frame's buffer, as an image, from the web cam / device
         * @returns A frames buffer as an image
         public Image grabFrameImage ( )
              Buffer buffer = grabFrameBuffer();
              if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    Image image = btoi.createImage ( buffer );
    return ( image );
              else
                   System.out.println ("Error : Buffer grabbed is null");
                   return ( null );
         * Closes and cleans up the player
         public void playerClose ( )
              if ( player != null )
         player.close();
         player.deallocate();
         player = null;
         public void windowClosing ( WindowEvent e )
              playerClose();
              System.exit ( 1 );
         public void componentResized(ComponentEvent e)
              Dimension dim = getSize();
              boolean mustResize = false;
              if ( dim.width < MIN_WIDTH )
              dim.width = MIN_WIDTH;
              mustResize = true;
              if ( dim.height < MIN_HEIGHT )
                   dim.height = MIN_HEIGHT;
                   mustResize = true;
              if ( mustResize )
                   setSize ( dim );
         public void windowActivated ( WindowEvent e )      {       }
         public void windowClosed ( WindowEvent e )      {       }
         public void windowDeactivated ( WindowEvent e )     {     }
         public void windowDeiconified ( WindowEvent e )     {     }
         public void windowIconified ( WindowEvent e )     {     }
         public void windowOpened ( WindowEvent e )          {     }
         public void componentHidden(ComponentEvent e)      {       }
         public void componentMoved(ComponentEvent e)     {     }
         public void componentShown(ComponentEvent e)     {     }
         protected void finalize     ( ) throws Throwable
              playerClose();
              super.finalize();
         class MyToolBarAction extends AbstractAction
              public MyToolBarAction ( String name, String imagefile )
                   super ( name, new ImageIcon ( imagefile ) );
              public void actionPerformed ( ActionEvent event )
                   toolbarHandler ( this );
         class MyVideoFormat
              public VideoFormat format;
              public MyVideoFormat ( VideoFormat _format )
                   format = _format;
              public String toString ( )
                   Dimension dim = format.getSize();
                   return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
         class MySnapshot extends JFrame
              protected Image photo = null;
              protected int shotNumber;
              public MySnapshot ( Image grabbedFrame, Dimension imageSize )
                   super ( );
                   shotNumber = shotCounter++;
                   setTitle ( "Photo" + shotNumber );
                   photo = grabbedFrame;
                   setDefaultCloseOperation ( WindowConstants.DO_NOTHING_ON_CLOSE );
                   int imageHeight = photo.getWidth ( this );
                   int imageWidth = photo.getHeight ( this );
                   setSize ( imageSize.width, imageSize.height );
                   final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
                   final JFrame thisCopy = this;
                   saveDialog.setFile ( "Photo" + shotNumber );
                   addWindowListener ( new WindowAdapter()
                             public void windowClosing ( WindowEvent e )
                                  saveDialog.show();
                                  String filename = saveDialog.getFile();
                                  if ( filename != null )
                                       if ( saveJPEG ( filename ) )
                                            JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
                                            setVisible ( false );
                                            dispose();
                                       else
                                            JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
                                  else
                                       setVisible ( false );
                                       dispose();
                   setVisible ( true );
              public void paint ( Graphics g )
                   g.drawImage ( photo, 0, 0, getWidth(), getHeight(), this );
              * Saves an image as a JPEG
              * @params the image to save
              * @params the filename to save the image as
         public boolean saveJPEG ( String filename )
              boolean saved = false;
         BufferedImage bi = new BufferedImage ( photo.getWidth(null),
         photo.getHeight(null),
         BufferedImage.TYPE_INT_RGB );
         Graphics2D g2 = bi.createGraphics();
         g2.drawImage ( photo, null, null );
         FileOutputStream out = null;
         try
         out = new FileOutputStream ( filename );
              JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
              JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
              param.setQuality ( 1.0f, false );
              encoder.setJPEGEncodeParam ( param );
              encoder.encode ( bi );
              out.close();
              saved = true;
         catch ( Exception ex )
         System.out.println ("Error saving JPEG : " + ex.getMessage() );
         return ( saved );
         }     // of MySnapshot
    public static void main (String[] args )
         try
              JWebCam myWebCam = new JWebCam ( "TimeSlice Web Cam Capture" );
              if ( myWebCam.initialise() )
                   // myWebCam.deviceInfo(); // outputs device info
              else
                   System.out.println ("Web Cam not detected / initialised");
         catch ( Exception ex )
              ex.printStackTrace();

    Doohhh... I posted an old version which didn't work.
    I tried and tested this last night, and it runs grand using Ver 2.1.1e.
    Tested under Windows 98, using an old Creative GO Camera.
    Haven't tried it under Linux, but suspect you'd have to at least change an references to "vfw" to "v4l".
    You'll need jmf.jar in your classpath to run it too.
    cheers,
    Owen
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture;         // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture;   // JMF 2.1.1e version
    public class JWebCam extends JFrame
        implements WindowListener,  ComponentListener
        protected final static int MIN_WIDTH  = 320;
        protected final static int MIN_HEIGHT = 240;
        protected static int shotCounter = 1;
        protected JLabel statusBar = null;
        protected JPanel visualContainer = null;
        protected Component visualComponent = null;
        protected JToolBar toolbar = null;
        protected MyToolBarAction formatButton    = null;
        protected MyToolBarAction captureButton   = null;
        protected Player player = null;
        protected CaptureDeviceInfo webCamDeviceInfo = null;
        protected MediaLocator ml = null;
        protected Dimension imageSize = null;
        protected FormatControl formatControl = null;
        protected VideoFormat currentFormat = null;
        protected Format[] videoFormats = null;
        protected MyVideoFormat[] myFormatList = null;
        protected boolean initialised = false;
         * Constructor
        public JWebCam ( String frameTitle )
            super ( frameTitle );
            try
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            catch ( Exception cnfe )
                System.out.println ("Note : Cannot load look and feel settings");
            setSize ( 320, 260 ); // default size...
            addWindowListener ( this );
            addComponentListener ( this );
            getContentPane().setLayout ( new BorderLayout() );
            visualContainer = new JPanel();
            visualContainer.setLayout ( new BorderLayout() );
            getContentPane().add ( visualContainer, BorderLayout.CENTER );
            statusBar = new JLabel ("");
            statusBar.setBorder ( new EtchedBorder() );
            getContentPane().add ( statusBar, BorderLayout.SOUTH );
         * Initialise
         * @returns true if web cam is detected
        public boolean initialise ( )
            throws Exception
            return ( initialise ( autoDetect() ) );
         * Initialise
         * @params _deviceInfo, specific web cam device if not autodetected
         * @returns true if web cam is detected
        public boolean initialise ( CaptureDeviceInfo _deviceInfo )
            throws Exception
            statusBar.setText ( "Initialising...");
            webCamDeviceInfo = _deviceInfo;
            if ( webCamDeviceInfo != null )
                statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                try
                    setUpToolBar();
                    getContentPane().add ( toolbar, BorderLayout.NORTH );
                    ml = webCamDeviceInfo.getLocator();
                    if ( ml != null )
                        player = Manager.createRealizedPlayer ( ml );
                        if ( player != null )
                            player.start();
                            formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                            videoFormats = webCamDeviceInfo.getFormats();
                            visualComponent = player.getVisualComponent();
                            if ( visualComponent != null )
                                visualContainer.add ( visualComponent, BorderLayout.CENTER );
                                myFormatList = new MyVideoFormat[videoFormats.length];
                                for ( int i=0; i<videoFormats.length; i++ )
                                    myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                                Format currFormat = formatControl.getFormat();
                                if ( currFormat instanceof VideoFormat )
                                     currentFormat = (VideoFormat)currFormat;
                                     imageSize = currentFormat.getSize();
                                     visualContainer.setPreferredSize ( imageSize );
                                     setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                                else
                                    System.err.println ("Error : Cannot get current video format");
                                invalidate();
                                pack();
                                return ( true );
                            else
                                System.err.println ("Error : Could not get visual component");
                                return ( false );
                        else
                            System.err.println ("Error : Cannot create player");
                            statusBar.setText ( "Cannot create player" );
                            return ( false );
                    else
                        System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
                        statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                        return ( false );
                catch ( IOException ioEx )
                    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                    return ( false );
                catch ( NoPlayerException npex )
                    statusBar.setText ("Cannot create player");
                    return ( false );
                catch ( CannotRealizeException nre )
                    statusBar.setText ( "Cannot realize player");
                    return ( false );
            else
                return ( false );
         * Dynamically create menu items
         * @returns the device info object if found, null otherwise
        public void setFormat ( VideoFormat selectedFormat )
            if ( formatControl != null )
                player.stop();
                imageSize = selectedFormat.getSize();
                formatControl.setFormat ( selectedFormat );
                player.start();
                statusBar.setText ( "Format : " + selectedFormat );
                currentFormat = selectedFormat;
                visualContainer.setPreferredSize ( currentFormat.getSize() );
                setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
            else
                System.out.println ("Visual component not an instance of FormatControl");
                statusBar.setText ( "Visual component cannot change format" );
        public VideoFormat getFormat ( )
            return ( currentFormat );
        protected void setUpToolBar ( )
            toolbar = new JToolBar();
            // Note : If you supply the 16 x 16 bitmaps then you can replace
            // the commented line in the MyToolBarAction constructor
            formatButton    = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
            captureButton   = new MyToolBarAction ( "Capture",    "BtnCapture.jpg" );
            toolbar.add ( formatButton );
            toolbar.add ( captureButton );
            getContentPane().add ( toolbar, BorderLayout.NORTH );
        protected void toolbarHandler ( MyToolBarAction actionBtn )
            if ( actionBtn == formatButton )
                Object selected = JOptionPane.showInputDialog (this,
                                                               "Select Video format",
                                                               "Capture format selection",
                                                               JOptionPane.INFORMATION_MESSAGE,
                                                               null,        //  Icon icon,
                                                               myFormatList, // videoFormats,
                                                               currentFormat );
                if ( selected != null )
                    setFormat ( ((MyVideoFormat)selected).format );
            else if ( actionBtn == captureButton )
                Image photo = grabFrameImage ( );
                if ( photo != null )
                    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
                else
                    System.err.println ("Error : Could not grab frame");
         * autoDetects the first web camera in the system
         * searches for video for windows ( vfw ) capture devices
         * @returns the device info object if found, null otherwise
        public CaptureDeviceInfo autoDetect ( )
            Vector list = CaptureDeviceManager.getDeviceList ( null );
            CaptureDeviceInfo devInfo = null;
            if ( list != null )
                String name;
                for ( int i=0; i<list.size(); i++ )
                    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                    name = devInfo.getName();
                    if ( name.startsWith ("vfw:") )
                        break;
                if ( devInfo != null && devInfo.getName().startsWith("vfw:") )
                    return ( devInfo );
                else
                    for ( int i = 0; i < 10; i++ )
                        try
                            name = VFWCapture.capGetDriverDescriptionName ( i );
                            if (name != null && name.length() > 1)
                                devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                                if ( devInfo != null )
                                    return ( devInfo );
                        catch ( Exception ioEx )
                            // ignore errors detecting device
                            statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
                    return ( null );
            else
                return ( null );
         * deviceInfo
         * @note outputs text information
        public void deviceInfo ( )
            if ( webCamDeviceInfo != null )
                Format[] formats = webCamDeviceInfo.getFormats();
                if ( ( formats != null ) && ( formats.length > 0 ) )
                for ( int i=0; i<formats.length; i++ )
                    Format aFormat = formats;
    if ( aFormat instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame(); );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) {   }
    public void windowClosed ( WindowEvent e ) {   }
    public void windowDeactivated ( WindowEvent e ) {   }
    public void windowDeiconified ( WindowEvent e ) {   }
    public void windowIconified ( WindowEvent e ) {   }
    public void windowOpened ( WindowEvent e ) {   }
    public void componentHidden(ComponentEvent e) {   }
    public void componentMoved(ComponentEvent e) {   }
    public void componentShown(ComponentEvent e) {   }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat _format )
    format = _format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MySnapshot extends JFrame
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "TimeSlice Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();

  • Place a JButton over the visualcomponent

    Hi to all.
    I'm a newbie to JMF.
    What I'm trying to do with no success is to add a permanent feature lets say a button on top
    of the visualComponent given from the player.
    It is impossible for the moment.
    I'm really desperate beacause I can't find a way out.
    For whom has already worked with JMF it sould be easy but not for my.
    Any hint or help Would be really wonderful
    Thanks to all in advance
    Mandy
    I Post here my code
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import com.sun.media.protocol.vfw.VFWCapture;
    public class MediaPlayer extends JFrame implements WindowListener,
    ComponentListener {
         private MenuBar mb;
         private Menu fileMenu;
         private Menu aboutMenu;
         private MenuItem aboutItem;
         private MenuItem exitItem;
         protected final static int MIN_WIDTH = 320;
         protected final static int MIN_HEIGHT = 240;
         protected static int shotCounter = 1;
         protected JLabel statusBar = null;
         protected JLayeredPane visualContainer = null;
         protected Component visualComponent = null;
         protected Player player = null;
         protected CaptureDeviceInfo webCamDeviceInfo = null;
         protected MediaLocator ml = null;
         protected Dimension imageSize = null;
         protected FormatControl formatControl = null;
         protected VideoFormat currentFormat = null;
         protected Format[] videoFormats = null;
         protected boolean initialised = false;
         * Costruttore *
         public MediaPlayer(String frameTitle) {
              super(frameTitle);
    //          dimensione della finestra
              Image icon = Toolkit.getDefaultToolkit().getImage("icona.gif");
              this.setIconImage(icon);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              this.setLocation(10 , 10);
              this.setSize(screenSize.width-100,screenSize.height-100);
              this.setResizable(false);
    // Add Menu Bar
              mb = new MenuBar();
              fileMenu = new Menu("File");
              mb.add(fileMenu);
              setMenuBar(mb);
              aboutMenu = new Menu("About");
              fileMenu.add(aboutMenu);
              AboutAction aboutAction = new AboutAction();
              aboutItem = new MenuItem("Application");
              aboutItem.addActionListener(aboutAction);
              aboutMenu.add(aboutItem);
              ExitAction action2 = new ExitAction();
              exitItem = new MenuItem("Exit");
              exitItem.addActionListener(action2);
              fileMenu.add(exitItem);
              addWindowListener(this);
              addComponentListener(this);
              getContentPane().setLayout(new BorderLayout());
              JPanel genericcontainer = new JPanel();
              //visualContainer = new JLayeredPane();
              //visualContainer.setLayout(new BorderLayout());
              visualContainer = new JLayeredPane();
              visualContainer.setBorder(BorderFactory.createTitledBorder(
    "STREAM VIEWER"));
              genericcontainer.add(visualContainer);
              getContentPane().add(genericcontainer, BorderLayout.CENTER);
              statusBar = new JLabel("");
              statusBar.setBorder(new EtchedBorder());
              getContentPane().add(statusBar, BorderLayout.SOUTH);
         * @restituisce true se viene trovata una webcam *
         public boolean initialise() throws Exception {
              return (initialise(autoDetect()));
         * @params _deviceInfo, informazioni sulla webcam rilevata * @restituisce
         * true se la webcam viene correttamente rilevata*
         public boolean initialise(CaptureDeviceInfo _deviceInfo) throws Exception {
              statusBar.setText("detecting WEBCAM");
              webCamDeviceInfo = _deviceInfo;
              if (webCamDeviceInfo != null) {
                   statusBar.setText("Connessione alla webcam : "
                             + webCamDeviceInfo.getName());
                   try {
                        ml = webCamDeviceInfo.getLocator();
                        if (ml != null) {
                             player = Manager.createRealizedPlayer(ml);
                             if (player != null) {
                                  player.start();
                                  formatControl = (FormatControl) player
                                  .getControl("javax.media.control.FormatControl");
                                  videoFormats = webCamDeviceInfo.getFormats();
                                  visualComponent = player.getVisualComponent();
                                  if (visualComponent != null) {
                                       visualContainer.setOpaque(false);
                                       visualContainer.add(visualComponent, new Integer(1));
                                       visualContainer.add(new JLabel("sssss"), new Integer(2));
                                       Format currFormat = formatControl.getFormat();
                                       if (currFormat instanceof VideoFormat) {
                                            currentFormat = (VideoFormat) currFormat;
                                            imageSize = currentFormat.getSize();
                                            visualContainer.setPreferredSize(imageSize);
                                            setSize(this.getSize().width, this.getSize().height
                                                      + statusBar.getHeight());
                                       } else {
                                            System.err
                                            .println("Errore nella rilevazione del formato video.");
                                       invalidate();
                                       pack();
                                       return (true);
                                  } else {
                                       System.err
                                       .println("Errore nella creazione della componente visiva.");
                                       return (false);
                             } else {
                                  System.err
                                  .println("Errore nella creazione del player.");
                                  statusBar.setText("Errore nella creazione del player.");
                                  return (false);
                        } else {
                             System.err.println("Nessun MediaLocator per: "
                                       + webCamDeviceInfo.getName());
                             statusBar.setText("Nessun MediaLocator per: "
                                       + webCamDeviceInfo.getName());
                             return (false);
                   } catch (IOException ioEx) {
                        statusBar.setText("Connessione a: "
                                  + webCamDeviceInfo.getName());
                        return (false);
                   } catch (NoPlayerException npex) {
                        statusBar.setText("Errore nella creazione del player.");
                        return (false);
                   } catch (CannotRealizeException nre) {
                        statusBar.setText("Errore nella realizzazione del player.");
                        return (false);
              } else {
                   return (false);
         * Cerca una webcam installata per Windows (vfw)*
         * @restituisce le informazioni sul device trovato
         public CaptureDeviceInfo autoDetect() {
              Vector list = CaptureDeviceManager.getDeviceList(null);
              CaptureDeviceInfo devInfo = null;
              if (list != null) {
                   String name;
                   for (int i = 0; i < list.size(); i++) {
                        devInfo = (CaptureDeviceInfo) list.elementAt(i);
                        name = devInfo.getName();
                        if (name.startsWith("vfw:")) {
                             break;
                   if (devInfo != null && devInfo.getName().startsWith("vfw:")) {
                        return (devInfo);
                   } else {
                        for (int i = 0; i < 10; i++) {
                             try {
                                  name = VFWCapture.capGetDriverDescriptionName(i);
                                  if (name != null && name.length() > 1) {
                                       devInfo = com.sun.media.protocol.vfw.VFWSourceStream
                                       .autoDetect(i);
                                       if (devInfo != null) {
                                            return (devInfo);
                             } catch (Exception ioEx) {
                                  statusBar
                                  .setText("Errore nella ricerca della webcam : "
                                            + ioEx.getMessage());
                        return (null);
              } else {
                   return (null);
         public void playerClose() {
              if (player != null) {
                   player.close();
                   player.deallocate();
                   player = null;
         public void windowClosing(WindowEvent e) {
              playerClose();
              System.exit(1);
         public void componentResized(ComponentEvent e) {
              Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
              setSize(dim.width-100,dim.height-100);
         public void windowActivated(WindowEvent e) {
         public void windowClosed(WindowEvent e) {
         public void windowDeactivated(WindowEvent e) {
         public void windowDeiconified(WindowEvent e) {
         public void windowIconified(WindowEvent e) {
         public void windowOpened(WindowEvent e) {
         public void componentHidden(ComponentEvent e) {
         public void componentMoved(ComponentEvent e) {
         public void componentShown(ComponentEvent e) {
         protected void finalize() throws Throwable {
              playerClose();
              super.finalize();
         public class ExitAction implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   playerClose();
                   System.exit(1);
         public class AboutAction implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   JFrame myframe = new JFrame();
              JOptionPane optionPane = new JOptionPane("\n" +
                        " Java Application\n" +
                        "\n" +
                        "Created by M.Zachariadou\n" +
                        "\n" +
                        " uses jre 1.6.0_3\n and JMF 2.1.1" +
                        "\n" +
         JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION);
         optionPane.createDialog(myframe, null).setVisible(true);
         public static void main(String[] args) {
              try {
                   MediaPlayer myWebCam = new MediaPlayer("Video Streaming from WEBCAM detected");
                   myWebCam.setVisible(true);
                   if (!myWebCam.initialise()) {
                        System.out.println("WebCam non trovata / inizializzata");
              } catch (Exception ex) {
                   ex.printStackTrace();
    }

    Yes. Make sure that you move it behide the control. To do so click on just
    the label then go to the reorder control on the toolbar and select move it
    backward or move it to back.
    -Tom
    "Mikey" wrote in message
    news:[email protected]..
    > I am trying to place text over the top of the round led control when I
    > do this I am unable to click on the control. Is there a way to make
    > the control translucent, so I can place it over the top the the text.
    > The control must be labled and they must be placed very close to one
    > another, not leaving enough roon to place the lable anywhere but on
    > the led. Is there a way to do something like this?

  • How to pass the caught exception in Thread.run back to the main program?

    I have following three Java files (simplified from a real world application I am developing, see files at the end of this posting):
    1. ThreadTest.java: The main program that invokes the Manager.run()
    2. Manager.java: The manager that creates a thread to execute the Agent.run() for each agent
    3. Agnet.java: The run() method can throw Exception
    My goal is twofold:
    1. To execute the run() method of an Agent in a thread (the reason for this is there are many Agents all managed by a Manager)
    2. To catch the exception thrown by Agent.run() in the main program, ThreadTest.main() -- so the main program can alert the exceptions
    My problem:
    Bottomline: I cannot pass the exception thrown by Agent.run() in the Thread.run() back to the main program.
    Explanation:
    The signature of Thread.run() (or Runnable.run()) is
    public void run();
    Since it does not have a throws clause, so I have to try/catch the Agent.run(), and rethrow a RuntimeException or Error. However, this RuntimeException or Error will not be caught by the main program.
    One work-around:
    Subclass the ThreadGroup, override the ThreaGroup.uncaughtException() methods, and spawn the threads of this group. However, I have to duplicate the logging and exception alerts in the uncaughtException() in addition to those already in the main program. This makes the design a bit ugly.
    Any suggestions? Am I doing this right?
    Thanks,
    Xiao-Li "Lee" Yang
    Three Java Files:
    // Agent.java
    public class Agent {
    public void run() throws Exception {
    throw new Exception("Test Exception"); // Agent can throw execptions
    // Manager.java
    public class Manager {
    public void run() throws Exception {
    try {         // <===  This try/catch is virtually useless: it does not catch the RuntimeException
    int numberOfAgents = 1;
    for (int i = 0; i < numberOfAgents; i++) {
    Thread t = new
    Thread("" + i) {
    public void run() {
    try {
    new Agent().run();
    } catch (Exception e) {
    throw new RuntimeException(e); // <=== has to be RuntimeException or Error
    t.start();
    } catch (Exception e) {
    throw new Exception(e); // <== never got here
    // ThreadTest.java
    public class ThreadTest {
    public static void main(String[] args) {   
    try {
    Manager manager = new Manager();
    manager.run();
    } catch (Throwable t) {
    System.out.println("Caught!"); // <== never got here
    t.printStackTrace();

    The problem is, where could you catch it anyway?
    try {
    thread.start();
    catch(SomeException e) {
    A thread runs in a separate, er, thread, that the catch(SomeException) isn't running within. Get it?
    Actually the Thread class (or maybe ThreadGroup or whatever) is the one responsible for invoking the thread's run() method, within a new thread. It is the one that would have to catch and deal with the exception - but how would it? You can't tell it what to do with it, it (Thread/ThreadGroup) is not your code.

  • Generic Exception handler in java

    We have developed a client java application with our own exception hierarchy derived from java.lang.exception. We raise our own exception in case of error scenarios. But there is one additional thing which we want to do:
    1. When ever any exception is raised in our exception we want to do some generic exception handling (like kicking of some module which collects the log files and send it to the administrator.
    2. We want the above activity to happen also when any runtime exception is raised. We are not catching any runtime exception and we have no handle for this.
    How should we go about this. Can we write a very low-level generic exception handler?
    We do not want to have done at every catch block we have in our code. I mean we want to have some hook at a very generic place.
    Let me know if some body can be help me on this.

    As far as I know, for exceptions that are caught, you must make a call to a generic handler in the catch block, or you may rethrow the exception as a RuntimeException, and let it propagate.
    For RuntimeExceptions and Errors in threads that you create, the easiest way to solve this is to subclass ThreadGroup, override uncaughtException with the appropriate code, and create all your threads in this group. For a thread like main, have the first thing in the thread be the creation of a new thread in the new group, then pass control to that thread. For fixed threads, like the event queue, someone had a suggestion already. Note that uncaughtException is only called just before the thread ends, so an exception that shouldn't end the thread should be handled seperately.

  • How to check internet connection available or not in adobe flash builder 4.6

    Hi
    Can you please help me for the above query.
    Thanks In Advance.

    rohit pathak wrote:
    iwhen internet is down , it throw an exception on Connection.connect() ,
    connect() is void type , it is not returning anything, that's why i can not handle itWhen an exception is thrown, you have two choices:
    1) Catch it and actually handle it. This means whatever failed, you have to make it work. Maybe by trying again, maybe be providing a default value.
    2) If you cannot to #1, then you should not catch the exception in the first place. Or, if you do catch it, wrap it and rethrow it.
    So, for example, in your case, if your code is:
    Establish connection.
    Use connection.If the "establish" part fails, you obviously can't do the "use" part, and this overall task has failed. That happens sometimes.

  • Release jms connection doesn?t release.

              Hi All,
              Environment: WLS 7.0sp2, JMS: weblogic JMS JMSJDBCStore, database oracle9
              We invoke the following sendEvent code from a worker thread invoked by a scheduler
              that was started in a servlet init method (this worker thread code is wrapped
              with a user tx).
              The topic’s MDB is getting the message OK, however the number of connection in
              the monitor (mydomain> JMS Servers> NomJMSServer> Active JMS Servers) keep growing.
              As you can see we are releasing the connection in a finally block. Can anybody
              explain it.?
              Second question: Should we cache the jms session? If the answer is yes, can they
              expire (close), how do we check if they are still valid?
              Thanks
              public String sendEvent(SyncOutput event)
              String retval = null;
              try
              init();
              topicPublisher.publish( formatMessage(event) );
              catch (Exception e)
              logger().debug("cannot send event", e);
              }finally{
              release();
              return retval;
              private Message formatMessage(SyncOutput output)
              throws JMSException, IOException
              BytesMessage message = topicSession.createBytesMessage();
              GZIPOutputStream gzip = new GZIPOutputStream(new BytesMessageOutputStream(message));
              output.flush(new OutputStreamWriter(gzip));
              gzip.close();
              return message;
              private void init()
              throws Exception
              InitialContext context = new InitialContext();
              TopicConnectionFactory conFactory =
              (TopicConnectionFactory) context.lookup(JMSConfig.get(JMSConfig.FACTORY));
              topicConnection = conFactory.createTopicConnection();
              topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
              Topic topic = (Topic) context.lookup( this.jndiName );
              topicPublisher = topicSession.createPublisher(topic);
              topicPublisher.setDeliveryMode(     DeliveryMode.PERSISTENT );
              private void release()
              try{
              if (topicPublisher != null){
              topicPublisher.close();
              topicPublisher = null;
              if (topicSession != null){
              topicSession.close();
              topicSession = null;
              if (topicConnection != null) {
              topicConnection.close();
              topicConnection = null;
              System.gc();
              }catch(Exception ignore){
              ignore.printStackTrace();
              

              We found the problem, it was a bug in our code. Thanks for your help.
              Tom Barnes <[email protected]> wrote:
              >Its possible the monitor has a bug, but in your case, since
              >you now only create one connection how could the
              >connection count keep growing?
              >
              >Perhaps the MDB app or MDB container is failing in some
              >unexpected way and not
              >closing its connection before attempting to create a new one?
              >Check your log for warnings and error messages, and
              >consider encapsulating your onMessage() code with a
              >try { /* all onMessage code */ }
              >catch (Throwable t) { t.printStackTrace(); rethrow}
              >
              >Meir wrote:
              >> Is it possible that the monitor has a bug? I changed my code to cache
              >the topic
              >> session and topic publisher, so I always use the same one (they are
              >static members
              >> of the class) but this didn't change the result that I'm seeing in
              >the monitor
              >> - the number of connections still keep growing.
              >> Could it be TX related weirdness (note we set the factory "User Transactions
              >Enabled"
              >> attribute to true)?
              >>
              >>
              >> "Meir" <[email protected]> wrote:
              >>
              >>>Thanks for your quick response.
              >>>I cahnged the code to catch throwable (both the open and close connection
              >>>are
              >>>in the try/catch block) and I don't see any problems.
              >>>Do you have any other suggestions? Do you need more data?
              >>>
              >>>
              >>>Tom Barnes <[email protected]> wrote:
              >>>
              >>>>
              >>>>Meir wrote:
              >>>>
              >>>>
              >>>>>Hi All,
              >>>>>
              >>>>>Environment: WLS 7.0sp2, JMS: weblogic JMS JMSJDBCStore, database
              >>>>
              >>>>oracle9
              >>>>
              >>>>>We invoke the following sendEvent code from a worker thread invoked
              >>>>
              >>>>by a scheduler
              >>>>
              >>>>>that was started in a servlet init method (this worker thread code
              >>>>
              >>>>is wrapped
              >>>>
              >>>>>with a user tx).
              >>>>>The topic’s MDB is getting the message OK, however the number of
              >connection
              >>>>
              >>>>in
              >>>>
              >>>>>the monitor (mydomain> JMS Servers> NomJMSServer> Active JMS Servers)
              >>>>
              >>>>keep growing.
              >>>>
              >>>>>As you can see we are releasing the connection in a finally block.
              >>>>
              >>>>Can anybody
              >>>>
              >>>>>explain it.?
              >>>>
              >>>>Perhaps you are throwing a RuntimeException or Error without
              >>>>catching it. Put trace statements before the connection
              >>>>create and right before and after the "connection.close()" to
              >>>>verify.
              >>>>
              >>>>Note that since you are closing the connection, there is no need
              >>>>to close the publisher or session.
              >>>>
              >>>>
              >>>>>Second question: Should we cache the jms session?
              >>>>
              >>>>For performance reasons, yes. But if your performance
              >>>>is fine, you don't need to. Since you are doing
              >>>>a "zip" per message, which is expensive in terms of CPU,
              >>>>the overhead of creating a session per
              >>>>message may be negligable in comparison.
              >>>>
              >>>>
              >>>>>If the answer is yes, can they
              >>>>>expire (close),
              >>>>
              >>>>If the host JMS server is adminstratively shutdown
              >>>>or the host JVM for the JMS server crashes...
              >>>>
              >>>>
              >>>>>how do we check if they are still valid?
              >>>>
              >>>>If it fails when you use it, it ain't valid. ;-)
              >>>>
              >>>>You can detect failures pro-actively by registering
              >>>>a connection onException listerner
              >>>>and a session onException listener.
              >>>>
              >>>>Note that WL 8.1 has built in connection/session
              >>>>pooling, and the JMS Performance Guide white-paper's
              >>>>appendix has sample code for writing your own pool for
              >>>>previous WL versions. There is a linke to
              >>>>the white-paper here:
              >>>>
              >>>>http://dev2dev.bea.com/technologies/jms/index.jsp
              >>>>
              >>>>
              >>>>>Thanks
              >>>>>
              >>>>>
              >>>>> public String sendEvent(SyncOutput event)
              >>>>> {
              >>>>> String retval = null;
              >>>>> try
              >>>>> {
              >>>>> init();
              >>>>> topicPublisher.publish( formatMessage(event) );
              >>>>> }
              >>>>> catch (Exception e)
              >>>>> {
              >>>>> logger().debug("cannot send event", e);
              >>>>> }finally{
              >>>>> release();
              >>>>> }
              >>>>> return retval;
              >>>>> }
              >>>>>
              >>>>> private Message formatMessage(SyncOutput output)
              >>>>> throws JMSException, IOException
              >>>>> {
              >>>>> BytesMessage message = topicSession.createBytesMessage();
              >>>>> GZIPOutputStream gzip = new GZIPOutputStream(new BytesMessageOutputStream(message));
              >>>>> output.flush(new OutputStreamWriter(gzip));
              >>>>> gzip.close();
              >>>>> return message;
              >>>>> }
              >>>>>
              >>>>> private void init()
              >>>>> throws Exception
              >>>>> {
              >>>>> InitialContext context = new InitialContext();
              >>>>> TopicConnectionFactory conFactory =
              >>>>> (TopicConnectionFactory) context.lookup(JMSConfig.get(JMSConfig.FACTORY));
              >>>>> topicConnection = conFactory.createTopicConnection();
              >>>>> topicSession = topicConnection.createTopicSession(false,
              >Session.AUTO_ACKNOWLEDGE);
              >>>>>
              >>>>> Topic topic = (Topic) context.lookup( this.jndiName );
              >>>>> topicPublisher = topicSession.createPublisher(topic);
              >>>>> topicPublisher.setDeliveryMode(     DeliveryMode.PERSISTENT );
              >>>>> }
              >>>>>
              >>>>> private void release()
              >>>>> {
              >>>>> try{
              >>>>> if (topicPublisher != null){
              >>>>> topicPublisher.close();
              >>>>> topicPublisher = null;
              >>>>> }
              >>>>>
              >>>>> if (topicSession != null){
              >>>>> topicSession.close();
              >>>>> topicSession = null;
              >>>>> }
              >>>>>
              >>>>> if (topicConnection != null) {
              >>>>> topicConnection.close();
              >>>>> topicConnection = null;
              >>>>> }
              >>>>>
              >>>>> System.gc();
              >>>>> }catch(Exception ignore){
              >>>>> ignore.printStackTrace();
              >>>>> }
              >>>>> }
              >>>>>
              >>>>
              >>
              >
              

  • Broken Pipe / Connection Reset Errors

    I know they come from the user hitting the stop button on his browser. They are benign and can be ignored. I just don't want to see them in my logs (or my email box) anymore. Anyone figure out how to disable the logging of these messages?
    ####<Jul 14, 2006 10:41:48 AM PDT> <Error> <HTTP> <test> <test-front_01> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1152898908905> <BEA-101017> <[weblogic.servlet.internal.WebAppServletContext@130c3e2 - name
    : 'singles_admin', context-path: '/singles_admin', version: 4.10.0.001] Root cause of ServletException.
    javax.servlet.jsp.JspException: ServletException in '/WEB-INF/jsp/common/header.jsp': Can't insert page 'menuheader.jsp' : Broken pipe
    at org.apache.struts.taglib.tiles.InsertTag$InsertHandler.doEndTag(InsertTag.java:921)
    at org.apache.struts.taglib.tiles.InsertTag.doEndTag(InsertTag.java:460)
    at jsp_servlet._web_45_inf._jsp._common.__userlayout._jspService(__userlayout.java:470)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:34)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:225)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:127)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:272)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:165)
    at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:496)
    at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:245)
    at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1056)
    at org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:261)
    at org.apache.struts.tiles.TilesRequestProcessor.processTilesDefinition(TilesRequestProcessor.java:237)
    at org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:300)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:231)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
    at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:397)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:225)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:127)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:272)
    at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42)
    at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:26)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3151)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:1973)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1880)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1310)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:179)
    >

    What I did to prevent the same issue was ensure all servlets had try/catch blocks where I ignored broken pipe exceptions and all JSPs had error pages that similarly ignored broken pipe exceptions. Worked 90% of the time. Had a couple of places where custom tags were catching exceptions, logging them, then rethrowing them that I had to fix (hopefully InsertTag isn't doing this). I think I ended up with only one place where I still had a problem, which was somewhere inside of WLS. Happened when the user closed their browser as WebLogic was writing back a large response, I believe. We just made sure our responses were as small as possible to avoid this. Stripped out white space from our JSPs during compilation and put a lot into CSS.

  • Unlock permissitic lock.

    Dear all,
    How to unlock a permissitic lock without rollback the transaction?
    The following code is trying to lock an array of object with a number of try. If anyone of the object is locked already, it will sleep for 1 sec and then retry again until the retry limit is reached. During the sleep I would like to release all acquired lock. The block of ???????? is where I want to release the acquired lock. However, I don't have any idea to do so without rollback the transaction. Thanks in advance for your help.
    private static boolean lockObjList(UnitOfWork uow, PersistenceObject[] refObjList, int numRetry)throws DomainServiceException{
    if (refObjList == null){
    return true;
    boolean sucessful = false;
    while (!sucessful && numRetry >= 0) {
    try {
    for (int i=0; i<refObjList.length; i++){
    PersistenceObject refObj = refObjList;
    // use LOCK_NOWAIT option to avoid deadlock.
    PersistenceObject refObjClone
    = (PersistenceObject)uow.refreshAndLockObject(refObj, ObjectLevelReadQuery.LOCK_NOWAIT);
    if (refObj.getVersion() != refObjClone.getVersion()){
    throw new Exception("One of the refered object has been modified.");
    sucessful = true;
    } catch (DatabaseException dbException){
    // check whether the exception is due to the locking.
    if (dbException.getCause() instanceof SQLException){
    SQLException sqlException = (SQLException)dbException.getCause();
    // currently, we assume "Oracle" database is used
    // the error code of cannot arquire the lock is 54.
    if (sqlException.getErrorCode() == 54){     
    numRetry --;     // retry again
    // release currently acquired lock.
    try {
    Thread.sleep(1000);// sleep for 1 second
    } catch (InterruptedException e) {}
    } else {
    // or rethrow the exception.
    throw dbException;     
    return sucessful;
    Thanks and regards,
    William

    The only way to release a lock is through commit or rollback. You need to begin the transaction inside of your operation so that you can rollback or re-try.
    There are also other ways you can accomplish locking a set of objects.
    - Lock all of the objects in a single query, this will ensure that all of the locks are acquire as a group.
    - Lock the entire table, inefficient but will either succeed or fail as a single operation.
    - Use SQL SAVEPOINTS to rollback just to the save point. Savepoints are not currently directly support by TopLink, but you can create one through SQL.
    i.e.
    uow.executeNonSelectingSQL("SAVEPOINT MYSAVEPOINT");
    uow.executeNonSelectingSQL("ROLLBACK TO SAVEPOINT MYSAVEPOINT");

  • How to check / internet is working or not?

    i need to execute a line of code in java console application only and only when internet is working ie i can access the google page
    to check the internet connection , i try below code,,
    try
            URL url = new URL("http://google.com/");
               URLConnection connection = url.openConnection();
               connection.connect();
            catch( Exception ex)
                // connection can not be established
            }but here, when internet is working, try block successfully execute . when internet is down , it throw an exception on Connection.connect() ,
    connect() is void type , it is not returning anything, that's why i can not handle it.... is there any other way , where i get true or false or any number , when internet is ok, ie www.google.com is responseing..

    rohit pathak wrote:
    iwhen internet is down , it throw an exception on Connection.connect() ,
    connect() is void type , it is not returning anything, that's why i can not handle itWhen an exception is thrown, you have two choices:
    1) Catch it and actually handle it. This means whatever failed, you have to make it work. Maybe by trying again, maybe be providing a default value.
    2) If you cannot to #1, then you should not catch the exception in the first place. Or, if you do catch it, wrap it and rethrow it.
    So, for example, in your case, if your code is:
    Establish connection.
    Use connection.If the "establish" part fails, you obviously can't do the "use" part, and this overall task has failed. That happens sometimes.

Maybe you are looking for

  • My FIOS TV only uses the Coax cable not the HDMI cable

    I can only get my STB to use the coax cable to my TV, I want it to use the HDMI cable for a better HD picture, but I do not see a way to get the STB to use the HDMI cable as the primary output. How do I tell my STB to use the HDMI cable instead of th

  • Abap - dump/job PSI_MECHANIK_2 (Program GP3KJGNMPNR0TSDBY8HHNGVSW8I010)

    Hello guys, I have a problem, I've got dump: job PSI_MECHANIK_2,...I have no idea why,... Anybody can help me??? Thanks, V. DUMP DESCRIPTION: An SQL error occurred when accessing a table. What happened? The database system detected a deadlock and avo

  • PDF showing different version on iphone than PC

    Hello, I received a PDF via email. When the pdf is opened on the PC and iphone, it shows different version, Can you give me the solution? Thanks Using iOS 5.0 and using Win7 for PC.

  • BAI2 file import showing debit as a credit after import

    We added a transaction code in FT "Auto generated bank statements" as a debit (decrease)  - payment processing of outgoing external payments. However when a bank statement is imported, the system picks it as a credit - other incoming payments. Not su

  • My First BURN!

    Okay... I'm a complete newbie and this is my first project with FCP. First time to ever use DVD Studio, as well. Heck... until this, I've never used ANY video editor! The footage I have is DVC PRO HD 720 24pn. Want to burn to a DVD, after making a me