JavaSide Tips
Main page
Home
[ Search | Home Page | Index Java tips ]


PrevRetour IndexNext
  • How to read an image (in an applet or application) without error message.

  • In an applet...
    tipsImg1.java : Download source or test applet
     // Importations
     import java.awt.Graphics ;
     import java.awt.Image ;
    
     public class tipsImg1 extends java.applet.Applet {
         // Variables
         Image img ;                 // ...
    
         // Init
         public void init() {                       // Methode init()
             // Read image
             // getCodeBase() is a base directory
             //    to read this image
              img =  getImage(getCodeBase(), "./photo.gif") ;
         }
    
         // Draw l'applet
         public void paint(Graphics g) {             // Methode paint()
              // Draw image at the position 5/10
              g.drawImage(img, 5, 10, this) ;
         }
      }
    This code makes it very simple to read and draw an image. You may receive a NullPointerException because this routine draws the image without testing if all the source images have been read.

  • Add a MediaTracker...
    tipsImg2.java : Download source or test applet
     // Import
     import java.awt.MediaTracker ;
    ....
         public void init() {   
              MediaTracker trk = new MediaTracker(this)  ;
    
             // Read image
              img =  getImage(getCodeBase(), "./photo.gif") ;
    
             // Add  image in a MediaTracker
              trk.addImage(img, 0) ;
    
             // Wait read data
              try {
                  trk.waitForAll() ;
              } catch (InterruptedException e) {
                    // Error...
              }
         }
    ...

  • With an application...
    tipsImg3.java : Download source or tipsImg3.zip application     (backup)
     // Import
     import java.awt.Toolkit ;
    ....
         public void init() {   
              MediaTracker trk = new MediaTracker(this)  ;
             // Recuperation du Toolkit de default de l'application
              Toolkit toolkit = Toolkit.getDefaultToolkit()  ;
    
             // Lecture de l'image
             // You must use a default toolkit with an application
              img =  toolkit.getImage("./photo.gif") ;
    
             // Add image in a MediaTracker
              trk.addImage(img, 0) ;
    
             // wait
              try {
                  trk.waitForAll() ;
              } catch (InterruptedException e) {
                    // Error...
              }
         }
    ...
    With an application you must use a toolkit to read an image (getCodeBase is not define ).





Copyright © 1996..2003, BERTHOU. All right reserved.
Last change : 05 March 2003 18H20