Creating simple animationsTopCreating and Drawing Geometric ObjectsCreating and Drawing Images

Creating and Drawing Images

Often we will want to import images into our program and draw them in a window. This takes a bit more work, and needs the following extra code.

  1. You first need to bring the image from a file into computer memory. Unfortunately it can take a (relatively) long time to bring an image from outside of memory (e.g., a jpeg or gif file), so after we request the item to be brought in, we may need to wait for it. I suggest you use the following method that I have written to make sure that the image is fully loaded before your program proceeds.
        /** 
         * Retrieve an image from file "filename", return the
         * Image when it has loaded completely.
         * @param the name of the file containing the image
         * @return the loaded Image.
         */
        private Image getCompletedImage(String fileName) {
           Toolkit toolkit = Toolkit.getDefaultToolkit();
           Image myImage = toolkit.getImage(fileName);
           MediaTracker mediaTracker = new MediaTracker(this);
           mediaTracker.addImage(myImage, 0);
           try {
              mediaTracker.waitForID(0);
           } catch (InterruptedException ie) {
              System.out.println(ie);
              System.exit(1);
           }
           return myImage;
        }
        

    Roughly, the method retrieves a default toolkit that has a method that will allow reading in an image in a file with name given by fileName. After the image is fetched with the getImage method, a MediaTracker object is created. The image is added to the media tracker object, which then waits for the loading of the image to be complete. If it fails to complete then an exception will be thrown and the program will exit. Otherwise, when the image is done loading, it will be returned from the method.

    You can try to do without the mediaTracker object, but if you try to access info about the image (e.g., ask its width or height), you might not get accurate information.

  2. Using the getCompletedImage method, an image can be loaded and displayed in a window with the following code:
            Image myImage = getCompletedImage("filename.jpg");
            g2.drawImage(flowerImage, x, y, this);
        

    where "filename.jpg" should be replaced by the name of the file holding the image. This code should be placed in a paint(g) method or in a method called from the paint method.


Creating simple animationsTopCreating and Drawing Geometric ObjectsCreating and Drawing Images