Images
Home Up Layout Managers Standard Graphics Images Event Handling UI Components

 

Images (and Double Buffering)

To display an image, do the following.  (Tip: if images are not loading fast enough, use the double buffering technique below or track the images through a MediaTracker object.)

  1.   Declare the image as an Image, e.g.

          Image myImage;
  2.   Load the actual image, e.g.

         myImage = getImage (getCodeBase(), "whatever.jpg");

    For this to work, a file named whatever.jpg must exist in the same directory as the Java class files that are executing.  The "getCodeBase()" method returns the directory of the Java class files.  Image files are typically suffixed by .jpg or .gif.
  3.   Display the image on the display window, e.g.

         g.drawImage(imageName, topLeftX, topLeftY, notificationObject);
    or  g.drawImage(imageName, topLeftX, topLeftY, width, height, notificationObject);

    The "imageName" is the name of the Image variable (e.g. "myImage") to display, the "topLeftX" specifies the X coordinate of the top left corner of the image (e.g. 0), the "topLeftY" specifies the Y coordinate of the top left corner of the image (e.g. 0), the "width" specifies the width of the image in pixels (e.g. 100), "height" specifies the height of the image in pixels (e.g. 50), and "notificationObject" specifies the object to notify when the image is finished loaded (e.g. this).  In the first version of this method, the values for "height" and "width" default to be the original size of the image.

Double Buffering

The idea behind double buffering is to write everything that you want to display on a secondary display buffer and then to display the secondary display buffer all at once.   When there are lots of images being displayed, this typically reduces flickering.   To employ double buffering, do the following:

  1.   Declare a secondary display surface, e.g.

         Image buffer;
  2.   Declare a graphics context for the buffer, e.g.

        Graphics bufferGraphics;
  3.   Set the size for the buffer, e.g.

       buffer = createImage(width, height);

    Where "width" specifies the width of the buffer in pixels and "height" specifies the height of the buffer in pixels.
  4.   Set the graphics context for the buffer, e.g.

       bufferGraphics = buffer.getGraphics();
  5.   Draw whatever you want to on the buffer, e.g.

       bufferGraphics.drawImage(imageName, topLeftX, topLeftY, notificationObject);
  6.   In the paint method, draw the buffer onto the display window, e.g.

       g.drawImage(buffer, topLeftX, topLeftY, notificationObject);