Steve - question on example #124

Steve, I've set up and run example #124 from your adf samples site. If I understand how it's supposed to work, then I think there's an issue with that example. When I first run TestPage, the page displays the first record (Id = 1) that was inserted via the sql script. RowType A (radio button) displays as selected, along with the inputtext and label for valueA. At this point, the inputtext is populated with AVALUE. So far so good. Clicking the RowType radio for B, the associated inputtext and label for valueB is displayed. This time, the inputtext has a null value, which is accurate according to the sql script i ran that accompanied this example. Now, click on radio button for RowType A again. This time, it's associated label and inputtext display, but the value is now null. I'm assuming that it should be back to AVALUE? Can you let me know what's going on here? I'm trying to use this example as a guide on how to implement conditional validation. Thanks, James.

See the following method in the entity object's java class:
    public void setRowType(String value) {
        setAttributeInternal(ROWTYPE, value);
        if (value !=null) {
            if (value.equalsIgnoreCase("A")) {
                setValueB(null);
            else if (value.equalsIgnoreCase("B")) {
                setValueA(null);
    }I consciously added that code to make it so that if the user set a value on "B", then the value of "A" got cleared and vice versa.

Similar Messages

  • Displaying Images in ADF/JSF: Error Using Steve Muench's Example #69

    Hi,
    I've been able to load images into the database using Steve Muench's Example 69. However, I'm having issues displaying the images.
    Jdeveloper: 10.1.3.3.0
    Database: 10gR2 with ORDSYS active.
    I'm getting the following error:
    07/08/20 12:09:20.993 JSFOrdImageExample-ViewController-webapp: Servlet error
    java.lang.NullPointerException
         at oracle.ord.html.OrdPlayMediaServlet.renderContent(OrdPlayMediaServlet.java:403)
         at oracle.ord.html.OrdPlayMediaServlet.deliver(OrdPlayMediaServlet.java:263)
         at oracle.ord.html.OrdPlayMediaServlet.doGet(OrdPlayMediaServlet.java:204)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
         at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:162)
         at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:623)
         at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:370)
         at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:871)
         at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:453)
         at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:221)
         at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.HttpRequestHandler.run(HttpRequestHandler.java:122)
         at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.HttpRequestHandler.run(HttpRequestHandler.java:111)
         at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
         at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
         at java.lang.Thread.run(Thread.java:613)I'm not sure why I'm getting a NullPointerException...
    Previous to this, I had to include the bc4jhtml.jar file as a library in application.xml, and I've tried using the two bc4jhtml.jar files, but neither one seems to work.
    I'm thinking that there must be something simple that I'm missing with the servlet setup...
    Thanks!
    Kenton

    I tried the wayback machine, but unfortunately, it doesn't cache the SWF files either :( I do have a copy of some (ok one) of Steve's old videos (the one that shows how to do a dropdown list in an editable table, back before it was easy to do), but unfortunately, none of the search ones.
    John

  • Questions about example "Dynamic JDBC Credentials for Model 1 and Model 2"

    Hello,
    i am trying to set up dynamic JDBC authentication in my ADF BC application - i want that it'll work like in Forms - a dababase user with the proper priveleges can log into my ADF BC application using his database login and password, and work with application.
    I've read the paper "How To Support Dynamic JDBC Credentials" at
    http://www.oracle.com/technology/products/jdev/howtos/10g/dynamicjdbchowto.html
    and test the very useful example, created by Steve Muench, which i've got from
    http://radio.weblogs.com/0118231/stories/2004/09/23/notYetDocumentedAdfSampleApplications.html#14
    The example works, but when i'm transfer its realisation in my application - it doesnt work the right way. The problems is the following:
    1. I can connect and work successfully only under the owner of the schema - the username and password of which i've wrote in the "jbo.server.internal_connection" string of the AM configuration.
    2. When i'm connecting under other users, which have all the rights to work with the db objects, used by application, i got the main page with the "Access Denied" message - as i have no priveleges to the tables.
    3. The big surprise is that if i am entering the fake username and password - the random letter combination - then i am getting the same behavior as in p.2 - the main page with the "Access Denied" message!
    And the last question is:
    4. Is it possible to set up the dynamic jdbc authentication using the build-in JDeveloper functions - i mean not to use that additional code, not override the ADF Binding Filter, and so on, but set up the similar behaviour (users log in using their db names and passwords) in several minutes following the standart documentation?
    Thanks in advance!

    One more question:
    I have 2 independent Application Modules in my application - to make the 2 transactions independent one form another, when working with different parts of project - and while using dinamic JDBC authentification, the user connects only in the first AM under the username he's entered, but the 2nd AM works under the predefined earlier (during development) connection for that AM.
    How can i make the 2nd AM to be connected under the logging in user (same as the 1rst AM)?

  • Question on example "configuring qllc to eth with local switching"

    Hello,
    I am reffering to the example on page
    http://www.cisco.com/en/US/partner/tech/tk331/tk336/technologies_configuration_example09186a0080093fba.shtml
    Let's consider that the Mainframe is on the ethernet side (OSA card) and the station on the serial side. Then I guess the example will work fine.
    To make things more complecated, now suppose that there is another station on another serial let say s0/1, with its own x.121 address, whereas the station is on s0/0. Now, if the station also wants to speak x.25 with the server on s0/1, how this could be accomplished? Does the configuration of the s0/0 with the x25 map and qllc dlsw commands, forbids the station from talking to other serial interfaces? Or if I just add a x.25 route to the s0/1, then whenever station asks for the x.121 address of the server it will be guided there?
    Regards, Apostolos.

    I am sorry but I think the question as it was set was a bit confusing. So, please let me rephrase it using the same example as basis. Let's consider we have two AS400 (a & b) connected with x25 to two serials on a router. This router is connected with a x.25 serial interface with another router, at serial s0/0, which has two connections:
    i) Ethernet to mainframe (OSA)
    ii) Serial (s0/1) x25 to another server (Stratus)
    AS400A is to speak with OSA card whereas AS400B is to speak with the stratus server.
    If I configure the serial interface to map x25 address of AS400A to a vmac and guide this to OSA, then will the other AS400B be able to connect to the Stratus?

  • 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();

  • Question on example from "Java concurrency in practice"

    "Java concurrency in practice" 14.9 listing ( [Orig here|http://www.javaconcurrencyinpractice.com/listings/ThreadGate.java] ):
    +...The condition predicate used by await is more complicated than simply testing isOpen. This is needed because if N threads are waiting at the gate at the time it is opened, they should all be allowed to proceed. But, if the gate is opened and closed in rapid succession, all threads might not be released if await examines only isOpen: by the time all the threads receive the notification, reacquire the lock, and emerge from wait, the gate may have closed again. So ThreadGate uses a somewhat more complicated condition predicate: every time the gate is closed, a "generation" counter is incremented, and a thread may pass await if the gate is open now or if the gate has opened since this thread arrived at the gate...+
    public class ThreadGate {
        private boolean isOpen;
        private int generation;
        public synchronized void close() {
            isOpen = false;
        public synchronized void open() {
            ++generation;
            isOpen = true;
            notifyAll();
        public synchronized void await() throws InterruptedException {
            int arrivalGeneration = generation;
            while (!isOpen && arrivalGeneration == generation) {
                wait();
    Question:
    Guys, could anyone explain me
    1) the work of code in term of "thread T1 waits, thread T2 closes..." the part arrivalGeneration == generation is unclear?
    2) Why both english and french editions say "every time the gate is closed, a generation counter is incremented"? How this is possible?
    3) Give an example how "the gate may have closed again" ? How this is possible?
    I posted this in other forums, but never had any explanations. Thanks.
    Edited by: maxim_2004 on Jul 14, 2010 9:19 AM

    Generation is a counter of how many times the gate has opened. We use it to determine if the gate has opened since a waiting thread arrived. The criteria for a waiting thread to proceed is not, "Is the gate open now?" but rather "Has the gate opened at least once since this thread started waiting?"
    Say you have N waiting threads and one controller thread. When the controller thread calls open(), we want all N waiting threads to be able to proceed. But the controller thread may call close() at any time, and depending on when he calls close(), how many waiting threads there are (that is, how large N is) and how the scheduler on that JVM/OS is operating, the controller thread may call close() before all of the waiting threads have completed the await() method.
    So a waiting thread may be stuck in the while loop call wait(), and by the time he has been notified, gets CPU cycles, acquires the lock, and goes back to test isOpen, the gate may have opened and closed. But we want him to be able to go, just because the gate did open. We don't care if he didn't get through before it closed again--he's supposed to be able to go anyway.
    Therefore, we don't just wait if the gate is closed. We wait if the number of times it has opened is the same as when we arrived. In other words we wait only, if it hasn't opened since this waiting thread arrived.
    Gate opens 1st time. (generation = 1)
    Gate closes.
    Gate opens 2nd time. (gen = 2)
    T2 arrives. (arrivalGen = 2)
    T2 calls wait()
    Gate opens 3rd time. (gen = 3)
    Gate closes.
    T2 gets CPU time and lock. Executes while test. Gate is closed. BUT gen=3 and arrivalGen=2, so even though the gate is closed now, it has opened since T2 arrived, so T2 is allowed to proceed (arrivalGen != gen)
    Edited by: jverd on Jul 14, 2010 10:05 AM
    Edited by: jverd on Jul 14, 2010 10:08 AM

  • 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();

  • Compile questions about example " DrawTest.java"

    i install the j2sdk1.4.0 with windows98 operations system.
    i want to recomplie the examples in c:\j2sdk1.4.0\demo\applets\DrawTest
    javac DrawTest.java
    12 errors occur as following:
    DrawTest.java:185: cannot resolve symbol
    symbol : variable orange
    location: class Color
    b.setForeground(Color.orange);
    ^
    DrawTest.java:188: cannot resolve symbol
    symbol : variable black
    location: class Color
    b.setForeground(Color.black);
    ^
    DrawTest.java:194: cannot resolve symbol
    symbol : variable lightGray
    location: class Color
    shapes.setBackground(Color.lightGray);
    ^
    DrawTest.java:200: cannot resolve symbol
    symbol : variable lightGray
    location: class Color
    g.setColor(Color.lightGray);
    ^
    12 errors
    how to solve this problem?
    thanks a lot

    Normally problems regarding cannot resolve symbol I've found are because the file you're working on uses another class file in the code, and the compiler from the prompt doesn't know where it's looking for the dependant classes. When compiling try using "javac -classpath "c:\whereyourclassesare" "c:\whereyourjavafileis.java""
    That should work, hopefully :)

  • Java logging questions - an example would really help

    We have taken over a project (i.e. we inherited someone else's code). I am relatively new to java. We would like to add debug messages or log messages to trace the application. Is there an easy way to insert debug messages and view the applicable log files?
    1.) I added the following code to add a debug message "log.error("Inside doResetPassword (" + userIdentification + ", " + newPassword + ")");"
    2.) Where is this log file located (what is the name of the log file)? Do I have to enable logging in Oracle? What are the steps to enable the logging? Is there a console that displays the log messages?
    Any help would be greatly appreciated ...
    Thanks,
    Mike
    public class AuthenticationListener implements Listener {
    private static final Log log = LogFactory.getLog(AuthenticationListener.class);
    PersonnelService personnelService;
    EmailService emailService;
    * Setter for Spring injection of {@link EmailService}.
    * @param emailService
    public void setEmailService(EmailService emailService) {
    this.emailService = emailService;
    * Setter for Spring injection of {@link PersonnelService}.
    * @param personnelService
    public void setPersonnelService(PersonnelService personnelService) {
    this.personnelService = personnelService;
    public void doResetPassword(String userIdentification, String newPassword) {
    Personnel personnel = personnelService.loadPersonnelById(Integer.parseInt(userIdentification));
    log.error("Inside doResetPassword (" + userIdentification + ", " + newPassword + ")");
    try {
    emailService.send(new PasswordEmail(personnel, newPassword));
    } catch (Exception e) {
    log.error("AuthenticationListener.doResetPassword: " + e.getMessage());
    }

    Hi,
    You should check out log4j. It's pretty easy to use, and has been the favorite logging tool for pretty much everyone I've worked with for the last few years. It's free, just google it.
    You won't have to change your java code, it plugs into the standard Java logging facility automatically.
    You just put log4j.jar and log4j.xml into your applib directory. Here is an example of a log4j.xml file that logs both to the console and to the file /logs/my.log. It assumes your code is in 'com.mypackage.' You can have as many logger elements as you want, and have different packages or classes set to different logging levels.
    <pre>
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
         <appender name="console" class="org.apache.log4j.ConsoleAppender">
              <param name="Target" value="System.out" />
              <layout class="org.apache.log4j.PatternLayout">
                   <param name="ConversionPattern" value="%d{HH:mm:ss,SSS} %-5p %C %m%n" />
              </layout>
         </appender>
         <appender name="file" class="org.apache.log4j.RollingFileAppender">
              <param name="File" value="/logs/my.log" />
         <param name="Append" value="true" />     
              <layout class="org.apache.log4j.PatternLayout">
                   <param name="ConversionPattern"
                        value="%d{HH:mm:ss,SSS} %-5p %c %m%n" />
              </layout>
         </appender>
         <logger name="com.mypackage">
              <level value="debug" />
         </logger>
         <root>
              <priority value="warn" />
              <appender-ref ref="console" />
              <appender-ref ref="file" />
         </root>
    </log4j:configuration>
    </pre>
    Hope that helps,
    Mike from Ottawa

  • Cascading windows question with example inside

    is there a way to force windows to not cascade past the bottom of the screen, like in CS3? i have to have my images in cascade form since i work on multiples of the same image spread out all over the place, but when i cascade 50 windows, the last dozen or so keep going until only the top few inches are showing and just go off to the right. any way to fix this? its like PS is not detecting the edge of my monitor somehow. any and all help is appreciated.

    is there a way to force windows to not cascade past the bottom of the screen, like in CS3? i have to have my images in cascade form since i work on multiples of the same image spread out all over the place, but when i cascade 50 windows, the last dozen or so keep going until only the top few inches are showing and just go off to the right. any way to fix this? its like PS is not detecting the edge of my monitor somehow. any and all help is appreciated.

  • License key question with regards to upgrading from 7/8.1 to 10

    Hi, I hope I've posted my question in the right area of the forum:
    I understand that Windows 10 will be a free upgrade for Win7/Win8 users.
    That's really wonderful but I was wondering what the exact mechanism with regards to our 7/8 license keys. Here's a couple examples to clarify my question:
    first, example: I have Windows 7 Pro license and say I upgrade to 10 within the first year. Let's say I need to reinstall Windows after that first year is finished will I still be able to use that same license key I used to upgrade 7 to 10 to install a fresh
    copy of Windows 10 or will I need to purchase a new license because the year is elapsed? 
    Here's another scenario. I upgrade to Windows 10 from 7 and after trying Windows 10 for while, I decide to uninstall 10 and go back to 7... because I'm crazy like that.... Will I be able to use my original Key for Windows 7 or is the upgrade a one way road:
    where the 7 key turns into a Windows 10 key and can no longer be used to activate Windows 7?
    Thanks for the feedback!

    Hi Momashi
    Here's another scenario. I upgrade to Windows 10 from 7 and after trying Windows 10 for while, I decide to uninstall 10 and go back to 7...
    because I'm crazy like that.... Will I be able to use my original Key for Windows 7 or is the upgrade a one way road: where the 7 key turns into a Windows 10 key and can no longer be used to activate Windows 7?
    If you Upgrade to Windows 10 and do not like it, for whatever reason.
    Before you upgrade to Windows 10.
    Create an image of windows 7 to an external HD and a recovery CD, using windows 7 Backup and Restore.
    You can re-install windows 7 in the SAME SYSTEM using the recovery CD without using  a key.
    Hope it helps
    Where did you get your outlandish information about a Windows 7 key turning into a Windows 10 key?  Nothing in the past has ever happened like this before, so what makes you think it will happen with Windows 10?
    My Windows ME did not turn into a Windows XP key!
    My Windows XP key did not turn into a Windows Vista key!
    My Windows Vista key did not turn into a Windows 7 key!
    And so on!
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. ”

  • I want to change the question order in my form, using TAB

    Hi,
    I'm trying to build a form in Adobe livecycle designer and I want to change the order of questions:  I want users to press TAB to switch question, but I have 2 columns and pressing Tab always brings me from left to right, then second line, I want second line until the end of the column and then change to right.....
    Example of what is the situation now:
    Header 1
    Header 2
    Question 1
    Question 2
    Question 3
    Question 4
    Question 5
    Question 6
    Question 7
    Question 8
    Example of what I want:
    Header 1
    Header 2
    Question 1
    Question 5
    Question 2
    Question 6
    Question 3
    Question 7
    Question 4
    Question 8
    Thanks for you help!

    Hi WWRACHELB,
    Try using custom order of fields in 'TAB Order' (window--> Tab Order) if that solves your problem.
    Regards,
    Ratnesh

  • Captivate 4 Questions coming up blank.

    I'm having some major problems with quiz answers not showing up.
    Just the Letters from the choices show on the slides (About 7 Questions slides mixed in the first 43 Slides, there are a total of about 85 slides)
    Muliple choice and single choice graded
    Questions slides after 43 all work correctly
    Check Boxes show
    Check boxes are unrelated to the the correct answers because when I mark the correct boxes I get the Incorrect answer texts.
    Captivate is running on Windows XP Pro 32 bit SP2.
    Captivate with latest update (build 1658)
    Published on two different XP Pro 32 bit machines with same result
    Publishing as AS3 script.
    I've resized the project at least once.
    I original had the project in it's infancy as a AS2 file in captivate 3 but quickly changed it to AS3 and captivate 4 with the preferences check boxes.
    I tried creating a new blank project and copied all slides into it, but the the slides at front still had problem.
    Edited on a third machine Vista 64 bit Captivate 4 Build 1658, added a question before slide 43, moved a question slide that was before slide 43 to end and published.  Saved CP file. All questions work now.
    Opened saved CP in XP Pro machines again and published. Slides before 43 all broken again. Interesting enough the question slide I moved to end still works.
    Both XP Pro machines have had Captivate 3 installed. On one, the Main editing machine Captivate 3 is still installed along with Captivate 4 on the other Captivate 3 was uninstalled and Captivate 4 added .
    I can not install SP3 of XP Pro.
    Captivate 4 is running as Administrator on the Vista 64 bit machine
    At one point I had edited the file on Captivate 4 Vista 64 bit and then brought back to the XP Pro Machine for final edits.
    How do I get this working in XP Pro 32 bit? Am I missing something between the two versions?  I think I could move all question slide to end and navigate back and forth but this is fragile at best. I wouldn't want to be trusting that this will work three weeks from now.

    I've ironed out a lot of the bugs in the questions
    now.  Had to move all the questions to the end of Captivate project and set all questions to only 1 try.
    I use advanced actions to jump to and away from the questions slides. Basically if I've been to the questions slides don't jump there, jump to the next slide. This action is run on the slide before the question, for example on slide 12 I must jump to slide 64 if I've not been to the question slide yet, other wise I jump to slide 13,. On the slide after the question set (A blank slide with a continue button, I use the same advanced action which will jump to slide 13 as I've just finished the questions).
    The questions being moved to the end of the project was done to get around the initial problem with Questions coming up blank earlier  in the project (About 1/3rd the way in, question slides would appear blank but when placed at the end of the project they would show up correctly and again only after I had moved to a Vista 64bit machine, not sure if the 64 bit operating system was a red herring but at the point of the move things that where not running started to run, including advanced actions).
    Each of my questions had 2 tries on them with two captions (The first caption to say that the response was wrong, try again and the second one to say incorrect the correct answers are.) After a certain point in the slides (even when moved to the end) two incorrect answers would stop the slide from advancing, to advance had to use the progress bar or multiple clicks on the Play button, clicking "anywhere" just wouldn't advance. I moved back to just a single try and the advancement problem disappeared. Hardly a real solution as I want the student to actually think about a incorrect answer as opposed to get the right answer no matter what they do. I didn't want to enable review as an alternative because I was having so many problems with slide movement as it was never mind adding review to the formula.
    I also had to simplify several complex animations that used the timeline. In a nut shell, one Continue or Next Slide button per slide. Working with multiple buttons at different timeline markers was unreliable. I found that occasionally you would have to click a second time on transparent buttons to advance the timeline. When this clicking problem happened I would find that some slides later, a transparent button programmed for next slide or Jump to Slide would instead jump back to the slide in which I had to click twice. As soon as you adjusted the timeline (which was more an act of praying too ones god) so that you only had to press it once,  both the the jumping back to the slide in question and the single click would work for a bit (Once it was working don't go there till it breaks again)
    Nihaar, I'll resubmit my working project to you so you can see the problems that still reside in the show. I'd love to not have to stand on one leg while juggling three balls and one machete. It would be nice to just have to stand on one leg, the machete and three balls just come unnaturally to me and I'm always afraid that I'll be left standing holding just one ball.
    Advanced actions:
    The following Advanced Action is for the final lesson final info slide, It jumps to the final question set (L7 Review 1)  or to the next slide (Congratulations slide) if the questions have been seen. The script also shows the play bar (First question slide of a set turns the play bar off). Note that Q7Complete is a user Variable. When you declare the variable set it's value to 1 (In some computer languages 0 can be problematic, so I, as a habit use 1).
    This Advanced Action is run on a button in the last info slide where you want to jump to the question or not  and on a blank "On Slide Enter" that you have added after the last question of the set. The "On Slide Exit" of the blank slide should be set at "No Action". If you forget to set the "No Action" the "On Slide Enter" advanced action will not navigate away from the blank slide properly.
    On each question set the first question slide,  set the "On Slide Enter" to set the cpCmndShowPlaybar = 0 to hide the play bar during the question slides.
    Please note that you should order the questions sets first to last when using this method. Do not mix up the order as I found that making questions mandatory (not a bug but a good feature) causes a problem in the navigation in and out of the question slides. Also ensure the person does not visit the questions a second time as this causes the questions already answered to reset. Each set of questions has it's own User Variable and Advanced Action.
    Check if   ( Q7Complete not equal to 2 )
    begin
              Q7Complete := 2
              Jump to slide L7 Review 1
    end
    or Else
      begin
             Q7Complete :=2
             cpCmndShowPlaybar := 1
             Jump to slide Congratulations
    End

  • Reporting model-layer warnings during renderModel (Steve #101 examaple)

    Hi!
    Everyone (almost ;) knows Steve's #101 example about reporting model-layer warnings to JSF.
    It works good, but there is one caveat: it doen't report warnings ussied before prepareModel phase and after invokeApplication phase.
    The first isn't a trouble, but the secons can turn in it.
    For example, the entity has auto calculated field and in case of calculating want to inform user a value was changed.
    In #101 i'му aded warning right in getDname() method:
    getDBTransaction().getRootApplicationModule().addWarning(new JboWarning("getDname() warning"));
    These warning doesn't appear on the first load to the testPage.jspx, inspite of it was added at model level during renderModel.
    On second render the warning apperar but because getDname() called twice (why twice?) during process validation phase.
    Does anybody faced the need of adding warnings at the renderModel phase? The cues will be apreciate...
    Thanks.
    Ilya Rodionov.

    Hi,
    Thanks for your quickly reply.I debuged my code in the two mode,first I run my application in the business component browser ,all warning are displayed as I desired .(both in base entity clase SXEntityImpl and concrete entity class applicationUserImpl)but when I run my jsf page (which include the same view object),only warning added in my concrete entity(appicationUserImpl.java) displayed on the screen.
    lixinzhu
    2007/09/27

  • SSAS aggregation question.

    I have a SSAS cube dimension with hierarchies - Country, State, City, Street.
    I have two measures (Price and Quantity) that need to aggregate independently up to City level only. Product (multiplication) of these two measures at City level should then be aggregated for higher level hierarchies (Country, State).
    How do I do this in MDX?
    Thanks,
    J.

    Hi,
    Here is my question with example:
    Dimension Hierarchy -  Country, State, City, Street.
    Country      State  City     Street      Qty
    US             CA      City1    Street1    10
    US             CA      City1    Street2     5
    US             FL       City3    Street3     8
    US             FL       City4    Street4     4
    Country       State       Plan      Price
    US              CA           A         $100
    US              CA           C         $70
    US              FL            B         $50
    Calculated Measure at Country level = 100*10 + 100*5 + 70*10 + 70*5 + 50*8 + 50*4 = 3150
    This is different from SUM(Price)*SUM(Qty) as it would be - 220*17 = 3740.
    I want 3150 to be my answer at Country level.
    I can JOIN the two table using Country and State fields to get a Cartesian product and that could works. The issue is the fact table becomes too big.

Maybe you are looking for