Source of MediaPanel.java


  1: // Fig 21.6: MediaPanel.java
  2: // A JPanel the plays media from a URL
  3: import java.awt.BorderLayout;
  4: import java.awt.Component;
  5: import java.io.IOException;
  6: import java.net.URL;
  7: import javax.media.CannotRealizeException;
  8: import javax.media.Manager;
  9: import javax.media.NoPlayerException;
 10: import javax.media.Player;
 11: import javax.swing.JPanel;
 12: 
 13: public class MediaPanel extends JPanel
 14: {
 15:    public MediaPanel( URL mediaURL )
 16:    {
 17:       setLayout( new BorderLayout() ); // use a BorderLayout
 18:       
 19:       // Use lightweight components for Swing compatibility
 20:       Manager.setHint( Manager.LIGHTWEIGHT_RENDERER, true );
 21:       
 22:       try
 23:       {
 24:          // create a player to play the media specified in the URL
 25:          Player mediaPlayer = Manager.createRealizedPlayer( mediaURL );
 26:          
 27:          // get the components for the video and the playback controls
 28:          Component video = mediaPlayer.getVisualComponent();
 29:          Component controls = mediaPlayer.getControlPanelComponent();
 30:          
 31:          if ( video != null ) 
 32:             add( video, BorderLayout.CENTER ); // add video component
 33: 
 34:          if ( controls != null ) 
 35:             add( controls, BorderLayout.SOUTH ); // add controls
 36:          
 37:          mediaPlayer.start(); // start playing the media clip
 38:       } // end try
 39:       catch ( NoPlayerException noPlayerException )
 40:       {
 41:          System.err.println( "No media player found" );
 42:       } // end catch
 43:       catch ( CannotRealizeException cannotRealizeException )
 44:       {
 45:          System.err.println( "Could not realize media player" );
 46:       } // end catch
 47:       catch ( IOException iOException )
 48:       {
 49:          System.err.println( "Error reading from the source" );
 50:       } // end catch
 51:    } // end MediaPanel constructor
 52: } // end class MediaPanel