這個 MyApplet.java 有許多個可以讓你很容易處理圖片和聲音的函數,
只要你 extends MyApplet 就可以使用,
那些寫 static 的函數則可以不必 extends MyApplet 就可使用,
當然要寫 MyApplet. 開頭, 例如 MyApplet.newCodeBase( ) 
注意所有  "new" 開頭的函數都只能用在 Java Application,
請先測試以下小程式 gga.java 再研究  MyApplet.java 
  //gga.java  --- test function in MyApplet.java
  import java.net.*;   // URL 在 java.net.*;
  class gga {
    public static void main(String yy[ ]) {
        URL g = MyApplet.newCodeBase( );
        String y = "" + g;
        y = y.replace("file:", "");   // 去掉 "file:" if any
        System.out.println("Your current directory is " + y);
    } // main(
  }// class
  // javac gga.java
  // java gga
  ///////////////////
 
   01 //MyApplet.java -- @CopyLeft by tsaiwn@csie.nctu.edu.tw 
   02 // provide some good utility functions for Applets
   03 // as long as some static utility functions for Applications
   04 //All functions begins with "new" are for Application only
   05 /// 
   06 import java.applet.*; 
   07 import java.awt.*;  import java.awt.image.*;
   08 import java.io.*; import java.net.*;
   09 import javax.swing.*;
   10   
   11 public class MyApplet extends Applet {  
   12 
   13    public MyApplet( ) {   // nothing to do
   14    }   // 裡面沒寫等於寫了 super( );  
   15 
   16    public void start( ) {
   17        Class o = getClass( ); // 抓出你的 class 名稱 
   18        printf("MyApplet_start: my class name from getclass( ) = "+ o +"\n");
   19        super.start( ); // 做 Applet 的 start( );  
   20    }
   21  
   22  /// newCodeBase() --- get the user's current working Directory
   23    static public URL newCodeBase( ) {    // for Application  
   24        URL codeBase = null;
   25        try {
   26           codeBase = new URL("file:" + System.getProperty("user.dir") + "/");
   27        } catch ( Exception e ) {
   28           // maybe it is an Applet, use getCodeBase() or getDocumentBase()
   29          /// but they only works in an Applet hosted in a Browser
   30        }
   31        return codeBase;
   32    }  
   33  /// same as newCodeBase() --- get the user's current working Directory
   34    static public URL getMyCodeBase( ) {    // for Application
   35        return newCodeBase( );
   36    }
   37  /// same as newCodeBase() --- get the user's current working Directory
   38    static public URL getCWD( ) {    // get Current Working Directory
   39        return newCodeBase( );
   40    }
   41   
   42  /// getPath, only works for Applet
   43    public URL getPath(String filename) {
   44       URL url = null;
   45           try {
   46              Toolkit tkt = Toolkit.getDefaultToolkit( );
   47              Class me = getClass( );   // get The class is running
   48              url = me.getResource(filename); // for Applet
   49           } catch ( Exception e2) {;} // ignore
   50       return url;
   51    }  
   52  /// newGetPath, static version of getPath   
   53    static public URL newGetPath(String filename) {  
   54       URL url = null;
   55           try {
   56              Toolkit tkt = Toolkit.getDefaultToolkit( );
   57              url = new URL( newCodeBase( ) + filename );
   58           } catch ( Exception e2) {;} // ignore
   59       return url;
   60    }
   61  
   62  /// getAudioBoth(filename) --- get AudioClip from Application or Applet
   63    public AudioClip getAudioBoth(String filename) {  
   64        AudioClip audio = null;
   65        try { // try Application first
   66           audio = newAudio(newCodeBase( ), filename);
   67        } catch (Exception e) { // then try Applet
   68        }
   69        if(audio == null) {   // try Applet
   70           try{ audio = getAudioClip(getCodeBase( ), filename);
   71           } catch ( Exception e ) {;}
   72        }
   73        return audio;   // send it back anyway
   74    } // getAudioBoth
   75   
   76  /// newAudio(filename) --- get AudioClip from an Application (not Applet)
   77    static public AudioClip newAudioStatic(String filename) {  
   78        AudioClip audio = null;
   79        try { 
   80           audio = newAudio(newCodeBase( ), filename);
   81        } catch (Exception e) { ; }
   82        return audio;
   83    } // newAudio(filename)
   84 ///  
   85    public AudioClip newAudioBoth(String filename) {  
   86        AudioClip audio = null;
   87        try {   // 2004/06/08
   88           Toolkit tkt = Toolkit.getDefaultToolkit( );
   89           Class me = getClass( );   // get The class is running
   90           URL url = me.getResource(filename);
   91           audio = Applet.newAudioClip( url );
   92        } catch (Exception e) { ; }
   93        return audio;
   94    } // newAudioBoth(filename)
   95  /// newAudio(url, filename)   
   96    static public AudioClip newAudio(URL base, String filename) {  
   97        AudioClip audio = null;
   98        try{ audio = Applet.newAudioClip( new URL(base+ filename) );
   99        } catch ( Exception e ) {
  100           // maybe it is an Applet, you should use getAudioClip(URL url) 
  101           // .. or getAudioClip(URL url, String filename)  in Applet
  102        }
  103        return audio;
  104    } // newAudio(url, filename)  
  105  /// newAudio(url)  --- get AudioClip from an Application (not Applet)
  106    static public AudioClip newAudio(URL url) {  
  107        AudioClip audio = null;
  108        try{ audio = Applet.newAudioClip( url );   // JDK1.2 static method
  109        } catch ( Exception e ) {;}
  110        return audio;
  111    } // newAudio(url)
  112  
  113   /// get Image from a local file --- for Application (not Applet)
  114    // Note that this is a static methods
  115    // usage: MyApplet.newImage("your_image_filename_path");
  116    static public Image newImage(String filename) {  
  117        Image image = null;
  118        try{
  119           Toolkit tkt = Toolkit.getDefaultToolkit( );
  120           image = tkt.getImage(filename);  //for application only
  121           // image = getImage(getCodeBase( ), filename); //for Applet
  122        } catch ( Exception e ) { image = null;}
  123        return image;
  124    } // newImage(filename)  
  125    static public Image newGetImage(String filename) {
  126       return newImage(filename);
  127    } // newGetImage
  128    static public Image getMyImage(String filename) {
  129        return newImage(filename);
  130    } // getMyImage(filename)
  131 
  132  /// get Image from a URL
  133    static public Image newImage(URL url) {   
  134        Image image = null;
  135        try{ Toolkit tkt = Toolkit.getDefaultToolkit( );
  136             image = tkt.getImage(url);  //for application only
  137        } catch ( Exception e ) {;}
  138        return image;
  139    } // newImage(url)   
  140    static public Image newGetImage(URL url) {  
  141       return newImage(url);
  142    } // newGetImage(url)
  143  
  144    /// @@@ 寫個 function to createMyCursor 方便使用@@@
  145   /// Application please uses Cursor mycsr = newMyCursor(filename);
  146   /// Applet please uses Cursor mycsr = createMyCursor(filename);
  147   ///
  148    /// now, this static method is for Application only
  149    static public java.awt.Cursor newMyCursor(String filename) throws
  150                                    IndexOutOfBoundsException {  
  151        java.awt.Cursor cursor = null;
  152        try{
  153           Toolkit tkt = Toolkit.getDefaultToolkit( );
  154           Image csrImg = tkt.getImage(filename);  //for application
  155           cursor = tkt.createCustomCursor(csrImg, new Point(1,1), filename);
  156        } catch ( Exception e ) { // if error, give him an Hand Cursor
  157           cursor = new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR);
  158        }
  159        return cursor;
  160    } // createMyCursor
  161  
  162   // now, the following is for Applet, not a static method
  163    public java.awt.Cursor createMyCursor(String filename) throws
  164                                    IndexOutOfBoundsException {  
  165        java.awt.Cursor cursor = null;
  166        try{
  167           Toolkit tkt = Toolkit.getDefaultToolkit( );
  168           //Image csrImg = tkt.getImage(filename);  //for application
  169           Image csrImg = getImage(getCodeBase( ), filename); //for Applet
  170           cursor = tkt.createCustomCursor(csrImg, new Point(1,1), filename);
  171        } catch ( Exception e ) {
  172           cursor = new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR);
  173        }
  174        return cursor;
  175    } // createMyCursor
  176  
  177    public java.awt.Cursor createMyCursorBoth(String filename) throws
  178                                    IndexOutOfBoundsException {  
  179        java.awt.Cursor cursor = null;
  180        try{
  181           Toolkit tkt = Toolkit.getDefaultToolkit( );
  182           Class me = getClass( );   // get The class is running
  183           URL url = me.getResource(filename);
  184           Image csrImg = tkt.getImage( url ); // works for Application+Applet
  185           cursor = tkt.createCustomCursor(csrImg, new Point(1,1), filename);
  186        } catch ( Exception e ) {
  187           cursor = new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR);
  188        }
  189        return cursor;
  190    } // createMyCursor
  191  
  192   // for both Application and Applet
  193    static public java.awt.Cursor createMyCursor(Image image) throws
  194                                    IndexOutOfBoundsException {  
  195        java.awt.Cursor cursor = null;
  196        try{
  197           Toolkit tkt = Toolkit.getDefaultToolkit( );
  198           cursor = tkt.createCustomCursor(image, new Point(1,1), "cursor");
  199        } catch ( Exception e ) {
  200           cursor = new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR);
  201        }
  202        return cursor;
  203    } // createMyCursor
  204   
  205    JLabel createLabelWithPicture(String filename) {
  206        return createLabelWithPicture(filename, "", 
  207                             javax.swing.SwingConstants.TRAILING);
  208    }
  209    JLabel createLabelWithPicture(String filename, String caption) {
  210        return createLabelWithPicture(filename, caption, 
  211                             javax.swing.SwingConstants.TRAILING);
  212    }
  213    JLabel createLabelWithPicture(String filename, String caption,
  214                                                   int alignment ) {  
  215       JLabel ans = null;
  216       ImageIcon icon = null;
  217       try {
  218          Image image = myGetImageBoth(filename);
  219          icon = new ImageIcon( image ); 
  220          ans = new JLabel(caption, icon, alignment);
  221          ans.setVerticalTextPosition(
  222                             javax.swing.SwingConstants.BOTTOM);
  223          ans.setHorizontalTextPosition(
  224                             javax.swing.SwingConstants.CENTER);
  225       } catch (Exception e) {
  226          try { if(ans==null) ans = new JLabel(caption);
  227          } catch (Exception e2) {;}
  228       }
  229       return ans;
  230    }
  231  
  232    /// some int constants used in the following functions  
  233      final static int TEXT_VP = javax.swing.SwingConstants.BOTTOM;
  234      final static int TEXT_HP = javax.swing.SwingConstants.CENTER;
  235      final static int IMG_V_ALIGN = javax.swing.SwingConstants.TOP;
  236      final static int IMG_H_ALIGN = javax.swing.SwingConstants.LEFT; 
  237    JButton createButtonWithPicture(String filename) {
  238       return createButtonWithPicture(filename, "",
  239                  TEXT_VP, TEXT_HP, IMG_V_ALIGN, IMG_H_ALIGN );
  240    }
  241    JButton createButtonWithPicture(String filename, String caption) {
  242       return createButtonWithPicture(filename, caption,
  243                  TEXT_VP, TEXT_HP, IMG_V_ALIGN, IMG_H_ALIGN );
  244    }
  245    JButton createButtonWithPicture(String filename, String caption,
  246                int textVP) {
  247       return createButtonWithPicture(filename, caption,
  248                  textVP, TEXT_HP, IMG_V_ALIGN, IMG_H_ALIGN );
  249    }
  250    JButton createButtonWithPicture(String filename, String caption,
  251                int textVP, int textHP ) {
  252       return createButtonWithPicture(filename, caption,
  253                  textVP, textHP, IMG_V_ALIGN, IMG_H_ALIGN );
  254    }
  255    JButton createButtonWithPicture(String filename, String caption,
  256                int textVP, int textHP, int imgVAlign ) {
  257       return createButtonWithPicture(filename, caption,
  258                  textVP, textHP, imgVAlign, IMG_H_ALIGN );
  259    }
  260    JButton createButtonWithPicture(String filename, String caption,
  261                int textVP, int textHP, int imgVAlign, int imgHAlign ) {  
  262       JButton ans = null;
  263       ImageIcon icon = null;
  264       try {
  265          Image image = myGetImageBoth(filename);
  266          icon = new ImageIcon( image ); 
  267          ans = new JButton(caption, icon);
  268            ans.setVerticalTextPosition(textVP);
  269            ans.setHorizontalTextPosition(textHP);
  270            ans.setVerticalAlignment(imgVAlign);
  271            ans.setHorizontalAlignment(imgHAlign);
  272       } catch (Exception e) {
  273          try { if(ans==null) ans = new JButton(caption);
  274          } catch (Exception e2) {;}
  275       }
  276       return ans;
  277    }
  278 
  279    Image getImageBoth(String filename) {
  280        return myGetImageBoth( filename);
  281    }
  282    Image myGetImageBoth(String filename) {  
  283       Image image = null;
  284       try {       // Application 中讀取 Image 方法與 Applet 中不同
  285          image = newImage(filename);   //try Application first
  286          //println("MyApplet got image=" + image);
  287       } catch (Exception e) { image=null; // then, try Applet
  288       } // try .. catch
  289       if(image==null) {
  290          try {       // try Applet, Applet use different method
  291             image = getImage(new URL( getCodeBase()+ filename));
  292          } catch (Exception e) { image = null;}
  293       } //if
  294       try { // ok, now the last way I can try
  295          Toolkit tkt = Toolkit.getDefaultToolkit( );
  296          Class me = getClass( );   // get The class which is running
  297          URL url = me.getResource(filename);
  298          image = tkt.getImage( url ); // works for both Application+Applet
  299       } catch (Exception e) { image = null; } // sorry, I have no way
  300       return image; 
  301    } // myGetImageBoth
  302   
  303  /// play an audio file (for Application only)
  304    static AudioClip newPlayFile(String filename) {  
  305        AudioClip song = null;
  306        try {
  307              URL base = newCodeBase();
  308              song = Applet.newAudioClip(new URL(base+filename)); 
  309           song.play( );
  310        } catch (Exception e) { return song; } // ignore any error
  311        try { Thread.sleep(358); } catch (Exception e) {;}
  312        return song;
  313    }
  314  
  315    public AudioClip playFile(String filename) {  
  316        AudioClip song = null;
  317        try {  
  318            //song = getAudioClip(getCodeBase(), filename);  // Applet's
  318            song = newAudioBoth(filename);  // both OK
  319            song.play( );
  320        } catch (Exception e) { return song; } // Let the caller know
  321        try { Thread.sleep(358); } catch (Exception e) {;}
  322        return song;
  323    }
  324 
  325    ///
  326   /// a utility to invoke the Task Manager (taskmgr) of Windows system
  327   // usage: MyApplet.runTaskManager( );   
  328    static void runTaskManager( ) {    // only works for Application only 
  329        printf("Try to run the Task Manager (taskmgr ) \n" );
  330        try {
  331              try {              // 注意格式, 因字串中含有 " 雙引號 "
  332                 Runtime.getRuntime().exec(
  333                   "cmd /c \"taskmgr"  + "\" " );
  334              } catch (Exception e95){
  335                 // to do : how to do on Win95/98 ?
  336              }  // Win95/98 ?
  337        } catch (Exception e) {; }
  338    } // run taskmgr
  339 
  340 
  341  /// 
  342 /// some println/print utilities for MyApplet, note that this is not static
  343 /// some println/print utilities for convinent
  344    static public void println(String s) {  
  345       try {  System.out.println(s);
  346       } catch (Exception e) {;} // ignore any error
  347    } 
  348    static public void print(String s) {     // not static  
  349       try {  System.out.print(s);
  350       } catch (Exception e) {;} // ignore any error
  351    } 
  352 /// some printErr utilities
  353    static public void printErr(String s) {  
  354       try {  System.err.println(s); System.err.flush( );
  355       } catch (Exception e) {;} // ignore any error
  356    } 
  357    static public void printf(String s) {  
  358       try {  System.out.print(s);
  359       } catch (Exception e) {;} // ignore any error
  360    } 
  361    public static void printf(long n) throws IOException {  
  362       System.out.print(""+n);
  363    } 
  364    public static void printf(int n) throws IOException {  
  365       System.out.print(""+n);
  366    } 
  367   /// print n as w columns width
  368    public static void printf(short n, int w) {   
  369       printf((long)n, w);   // print n as w columns
  370    }
  371    public static void printf(int n, int w) {
  372       printf((long)n, w);
  373    } 
  374    public static void printf(long n, int w) {  
  375       long tmp = 1;   // print n as w columns
  376       long nabs = n; if(n<0) {nabs = -nabs; --w; }  // ensure positive
  377       for(;;) {
  378           tmp *= 10;
  379           if(tmp > nabs) break;
  380           --w;    // w is the expected Width (number of digits)
  381       }
  382       try {
  383          for(;;) {
  384              if(--w <= 0) break;
  385              System.out.print(" ");   // necessary leading space
  386          }
  387          System.out.print(""+n);
  388       } catch (Exception e) {;} // ignore any error
  389    }
  390  
  391    public void flush( ) {  
  392 	   try { System.out.flush( );
  393       } catch (Exception e) {;} // ignore any error
  394    }
  395  
  396    static public void fflush( ) {  
  397       try { System.out.flush( );
  398       } catch (Exception e) {;} // ignore any error
  399    }
  400  
  401    static public void beep( ) {  
  402      java.awt.Toolkit.getDefaultToolkit( ).beep( );
  403    }
  404  
  405   /// a main program to test my printf functions
  406    public static void main(String[]p) throws IOException {
  407        printf("= This MyApplet.java provides many utility functions =\n");
  408        printf("=="); printf(1, 1); printf("==\n");
  409        printf("=="); printf(2, 2); printf("==\n");
  410        printf("=="); printf(3, 3); printf("==\n");
  411        printf("=="); printf(11, 1); printf("==\n");
  412        printf("=="); printf(12, 2); printf("==\n");
  413        printf("=="); printf(13, 3); printf("==\n");
  414        printf("=="); printf(111, 1); printf("==\n");
  415        printf("=="); printf(113, 3); printf("==\n");
  416        printf("=="); printf(115, 5); printf("==\n");
  417        printf("=="); printf(-11, 1); printf("==\n");
  418        printf("=="); printf(-12, 2); printf("==\n");
  419        printf("=="); printf(-13, 3); printf("==\n");
  420        printf("=="); printf(-15, 5); printf("==\n");
  421        printf("=="); printf(-116, 6); printf("==\n");
  422        try {
  423           AudioClip sound = null; sound = newAudioStatic("laugh.au");
  424           if(sound != null) { sound.play( ); Thread.sleep(2588); }
  425        } catch(Exception e) {;}
  426        printf("Thank you!\n"); 
  427        for(int i=1; i <= 3; ++i) {
  428           java.awt.Toolkit.getDefaultToolkit( ).beep( );
  429           try{ Thread.sleep(258);}catch(Exception e){;}  // 0.258 second
  430        }
  431        System.exit(0);
  432    }
  433 } // class MyApplet
  434   
  435 class PictureCanvas extends Canvas implements ImageObserver { 
  436    String filename = null;
  437    String caption = null;
  438    Image image = null;
  439    public PictureCanvas(String filename) {
  440       this(filename, "");   // call other Constructor
  441    } 
  442    public PictureCanvas(String filename, String caption) { 
  443       this.filename = filename;
  444       this.caption = caption;
  445       try {
  446          Toolkit tkt = Toolkit.getDefaultToolkit( );
  447          Class me = getClass( );   // get The class is running
  448          URL url = me.getResource(filename);
  449          image = tkt.getImage( url ); // works for both Application+Applet
  450       } catch (Exception e) { ; }
  451       repaint( ); 
  452    }
  453    public void update(Graphics g) {
  454        paint(g);   // call paint directly without clear the panel
  455    } 
  456    public void paint(Graphics g) {
  457       int xpos = 12, ypos = 12;
  458       if(image!=null) {
  459          g.drawImage(image, 2, 2, this );     // Align left-upper corner
  460          try {
  461             xpos = image.getWidth(this)/4;
  462             ypos = image.getHeight(this) - 24;
  463          }catch(Exception e) {;}
  464       }
  465       if(caption != null) {
  466           g.setFont(new Font("細明體", Font.PLAIN, 18) );
  467           g.setColor(Color.red);
  468           g.drawString( caption, xpos, ypos );
  469       }
  470    } // paint 
  471 } // PictureCanvas
  472  
  473 class PicturePanel extends Panel {  
  474    String filename = null;
  475    String caption = null;
  476    Image image = null;
  477    boolean wantResize = false;   
  478    public PicturePanel(String filename, boolean wantResize) {
  479       this(filename, "", wantResize);   // call other Constructor
  480    }
  481    public PicturePanel(String filename) {
  482       this(filename, "", false);   // call other Constructor
  483    }
  484    public PicturePanel(String filename, String caption) {
  485       this(filename, caption, false);   // call other Constructor
  486    }
  487    public PicturePanel(String filename, String caption, boolean w) {  
  488       this.wantResize = w;
  489       this.filename = filename;
  490       this.caption = caption;
  491       try {
  492          Toolkit tkt = Toolkit.getDefaultToolkit( );
  493          Class me = getClass( );   // get The class is running
  494          //MyApplet. printf(" getClass() = " + me +"\n");
  495          URL url = me.getResource(filename);
  496          image = tkt.getImage( url ); // works for both Application+Applet
  497         // Only those Applets hosted in a Browser can obtain CodeBase
  498         /// .. and DocumentBase using getCodeBase( ) and getDocumentBase( )
  499         /// .. Since this PicturePanel is not an Applet, the
  500         /// method getCodeBase() doesn't work even you call it from an Applet
  501       } catch (Exception e) { ; }
  502       repaint( ); 
  503    }
  504    public void update(Graphics g) {
  505        paint(g);   // call paint directly without clear the panel
  506    } 
  507    public void paint(Graphics g) {
  508       int xpos = 12, ypos = 12;
  509       if(image!=null) {
  510          int width = 0;
  511          int height = 38;
  512          try {
  513             width = image.getWidth(this);   // image's width
  514             height = image.getHeight(this);
  515          } catch (Exception e) {;}
  516          if(wantResize)
  517          try {
  518              width = getSize().width;   // current Panel's width
  519              height = getSize().height;
  520          } catch (Exception e) {;}
  521          if(width == 0)
  522             g.drawImage(image, 2, 2, this );     // Align left-upper corner
  523          else
  524             g.drawImage(image, 2, 2, width, height, this );  
  525       // now paint the caption
  526          try {
  527             xpos = image.getWidth(this)/4;
  528             ypos = image.getHeight(this) - 24;
  529          }catch(Exception e) {;}
  530       }
  531       if(caption != null) {
  532           g.setFont(new Font("細明體", Font.PLAIN, 18) );
  533           g.setColor(Color.red);
  534           g.drawString( caption, xpos, ypos );
  535       }
  536    } // paint  
  537 } // PicturePanel