• Support PF! Buy your school textbooks, materials and every day products Here!

JAVA Animated Logo DUE TODAY HELP!

  • Comp Sci
  • Thread starter iamjon.smith
  • Start date
  • #1
117
3
JAVA Animated Logo **DUE TODAY** HELP!

My instructor has provided the code to use, we were told to simply modify the images for the program to work with our logo. The code comes straight from the text book.

I have followed the steps of my instructor but when I run the program I get the following error:

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:167)
at LogoAnimatorJPanel.<init>(LogoAnimatorJPanel.java:39)
at LogoAnimator.main(LogoAnimator.java:19)
Java Result: 1


Code is as follows:
class
Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jon and Jessica
 */
// Fig. 21.2: LogoAnimatorJPanel.java
// Animation of a series of images.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;

public class LogoAnimatorJPanel extends JPanel
{
   private final static String IMAGE_NAME = "1"; // base image name
   protected ImageIcon images[]; // array of images
   private final int TOTAL_IMAGES = 112;   // number of images
   private int currentImage = 0; // current image index
   private final int ANIMATION_DELAY = 50; // millisecond delay
   private int width; // image width
   private int height; // image height

   private Timer animationTimer; // Timer drives animation

   // constructor initializes LogoAnimatorJPanel by loading images
   public LogoAnimatorJPanel()
   {
      images = new ImageIcon[ TOTAL_IMAGES ];

      // load 30 images
      for ( int count = 0; count < images.length; count++ )
         images[ count ] = new ImageIcon( getClass().getResource(
            "Images/" + IMAGE_NAME + count + ".png" ) );

      // this example assumes all images have the same width and height
      width = images[ 0 ].getIconWidth();   // get icon width
      height = images[ 0 ].getIconHeight(); // get icon height
   } // end LogoAnimatorJPanel constructor

   // display current image
   public void paintComponent( Graphics g )
   {
      super.paintComponent( g ); // call superclass paintComponent

      images[ currentImage ].paintIcon( this, g, 0, 0 );

      // set next image to be drawn only if Timer is running
      if ( animationTimer.isRunning() )
         currentImage = ( currentImage + 1 ) % TOTAL_IMAGES;
   } // end method paintComponent

   // start animation, or restart if window is redisplayed
   public void startAnimation()
   {
      if ( animationTimer == null )
      {
         currentImage = 0; // display first image

         // create timer
         animationTimer =
            new Timer( ANIMATION_DELAY, new TimerHandler() );

         animationTimer.start(); // start Timer
      } // end if
      else // animationTimer already exists, restart animation
      {
         if ( ! animationTimer.isRunning() )
            animationTimer.restart();
      } // end else
   } // end method startAnimation

   // stop animation Timer
   public void stopAnimation()
   {
      animationTimer.stop();
   } // end method stopAnimation

   // return minimum size of animation
   public Dimension getMinimumSize()
   {
      return getPreferredSize();
   } // end method getMinimumSize

   // return preferred size of animation
   public Dimension getPreferredSize()
   {
      return new Dimension( width, height );
   } // end method getPreferredSize

   // inner class to handle action events from Timer
   private class TimerHandler implements ActionListener
   {
      // respond to Timer's event
      public void actionPerformed( ActionEvent actionEvent )
      {
         repaint(); // repaint animator
      } // end method actionPerformed
   } // end class TimerHandler
} // end class LogoAnimatorJPanel

/**************************************************************************
 * (C) Copyright 1992-2007 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. All Rights Reserved.                           *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/
main class:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jon and Jessica
 */
// Fig. 21.3: LogoAnimator.java
// Animation of a series of images.
import javax.swing.JFrame;

public class LogoAnimator
{
   // execute animation in a JFrame
   public static void main( String args[] )
   {
      LogoAnimatorJPanel animation = new LogoAnimatorJPanel();

      JFrame window = new JFrame( "Animator test" ); // set up window
      window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      window.add( animation ); // add panel to frame

      window.pack();  // make window just large enough for its GUI
      window.setVisible( true );   // display window

      animation.startAnimation();  // begin animation
   } // end main
} // end class LogoAnimator

/**************************************************************************
 * (C) Copyright 1992-2007 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. All Rights Reserved.                           *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/
I am using a folder named Images to contain all of the images for the animation. The images are named "1" through "113" respectively, for a total of 113 images. They were created in paint and are .png images. I have included the first three images as attachments for you to use.

Please, help me as soon as possible. I just need to be pointed in the right direction. I have run the debugger and set breakpoints to try and figure out what is wrong, but I am lost in the sauce.
 

Attachments

Answers and Replies

  • #2
297
2


I haven't compiled it or tried it, but I think I see the problem.

You say the images are numbered 1 to 113. Your loop seems to be starting at 0. There probably isn't an image numbered 0. Also make sure you get to 113. As it is, it won't reach the last image.

If that's not it, I can take a closer look.

EDIT: IMAGE_NAME also doesn't look like it should be concatenated into the filename to me. Also should be TOTAL_IMAGES = 113, no?
 
Last edited:
  • #3
117
3


If I understand what the instructor told us correctly, the loop starts at 0 because the array is indexed 0 - 112, total of 113.

IMAGE_NAME also doesn't look like it should be concatenated into the filename to me. Also should be TOTAL_IMAGES = 113, no?
Not really sure what part this has to play, but was told it was necessary. I asked the instructor the same question about the error, and was told: "I believe that if you put a breakpoint in the debugger at line 39 in the LogAnimatorJPanel you will most likely see that the name of the image that you are trying to load does not match the image name in the folder."

I have gone back and renamed the images and made a few additional changes, but still get the same error.

Code:
// load 113 images
      for ( int count = 0; count < images.length; count++ )
         images[ count ] = new ImageIcon( getClass().getResource(
            "Images/" + IMAGE_NAME + count + ".png" ) );
which is where the debugger points to, but I can't find the problem.

If you could, compile using the three included images I attached and see what you can figure out. I am still struggling through on this end trying to figure out what is going on, but no luck so far. Thank you for the reply also.

new code is as follows:
LogoAnimatorJPanel:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jon and Jessica
 */
// Fig. 21.2: LogoAnimatorJPanel.java
// Animation of a series of images.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;

public class LogoAnimatorJPanel extends JPanel
{
   private final static String IMAGE_NAME = "logo"; // base image name
   protected ImageIcon images[]; // array of images
   private final int TOTAL_IMAGES = 113;  // number of images
   private int currentImage = 0; // current image index
   private final int ANIMATION_DELAY = 50; // millisecond delay
   private int width; // image width
   private int height; // image height

   private Timer animationTimer; // Timer drives animation

   // constructor initializes LogoAnimatorJPanel by loading images
   public LogoAnimatorJPanel()
   {
      images = new ImageIcon[ TOTAL_IMAGES ];

      // load 113 images
      for ( int count = 0; count < images.length; count++ )
         images[ count ] = new ImageIcon( getClass().getResource(
            "images/" + IMAGE_NAME + count + ".png" ) );

      // this example assumes all images have the same width and height
      width = images[ 0 ].getIconWidth();   // get icon width
      height = images[ 0 ].getIconHeight(); // get icon height
   } // end LogoAnimatorJPanel constructor

   // display current image
   public void paintComponent( Graphics g )
   {
      super.paintComponent( g ); // call superclass paintComponent

      images[ currentImage ].paintIcon( this, g, 0, 0 );

      // set next image to be drawn only if Timer is running
      if ( animationTimer.isRunning() )
         currentImage = ( currentImage + 1 ) % TOTAL_IMAGES;
   } // end method paintComponent

   // start animation, or restart if window is redisplayed
   public void startAnimation()
   {
      if ( animationTimer == null )
      {
         currentImage = 0; // display first image

         // create timer
         animationTimer =
            new Timer( ANIMATION_DELAY, new TimerHandler() );

         animationTimer.start(); // start Timer
      } // end if
      else // animationTimer already exists, restart animation
      {
         if ( ! animationTimer.isRunning() )
            animationTimer.restart();
      } // end else
   } // end method startAnimation

   // stop animation Timer
   public void stopAnimation()
   {
      animationTimer.stop();
   } // end method stopAnimation

   // return minimum size of animation
   public Dimension getMinimumSize()
   {
      return getPreferredSize();
   } // end method getMinimumSize

   // return preferred size of animation
   public Dimension getPreferredSize()
   {
      return new Dimension( width, height );
   } // end method getPreferredSize

   // inner class to handle action events from Timer
   private class TimerHandler implements ActionListener
   {
      // respond to Timer's event
      public void actionPerformed( ActionEvent actionEvent )
      {
         repaint(); // repaint animator
      } // end method actionPerformed
   } // end class TimerHandler
} // end class LogoAnimatorJPanel

/**************************************************************************
 * (C) Copyright 1992-2007 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. All Rights Reserved.                           *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/
I also renamed all images to have logo preceding the number (logo1, logo2, logo3, etc.)
 
Last edited:
  • #4
297
2


Code:
// load 113 images
      for ( int count = 0; count < images.length; count++ )
         images[ count ] = new ImageIcon( getClass().getResource(
            "Images/" + IMAGE_NAME + count + ".png" ) );
Ok, makes sense to start at 0 for the array index. But the filename created would still be incorrect. For image 1 (with count = 0), I would expect that to create this filename:

Images/logo0.png

Perhaps try this:

Code:
// load 113 images
      for ( int count = 0; count < images.length; count++ )
         images[ count ] = new ImageIcon( getClass().getResource(
            "Images/" + IMAGE_NAME + (count+1) + ".png" ) );
You'll want the count to go from 0 to 112 (thus files numbered 1 to 113). So TOTAL_IMAGES should be 113. The loop will thus exit after handling 112 (file 113).
 
  • #5
117
3


Ok, makes sense to start at 0 for the array index. But the filename created would still be incorrect. For image 1 (with count = 0), I would expect that to create this filename:

Images/logo0.png

Perhaps try this:

Code:
// load 113 images
      for ( int count = 0; count < images.length; count++ )
         images[ count ] = new ImageIcon( getClass().getResource(
            "Images/" + IMAGE_NAME + (count+1) + ".png" ) );
You'll want the count to go from 0 to 112 (thus files numbered 1 to 113). So TOTAL_IMAGES should be 113. The loop will thus exit after handling 112 (file 113).
When I make that change, I get a whole new list of issues:
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:41)
at java.awt.image.Raster.createPackedRaster(Raster.java:458)
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1015)
at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:230)
at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:484)
at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:120)
at sun.awt.image.PNGImageDecoder.sendPixels(PNGImageDecoder.java:531)
at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:452)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:41)
at java.awt.image.Raster.createPackedRaster(Raster.java:458)
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1015)
at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:230)
at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:484)
at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:120)
at sun.awt.image.PNGImageDecoder.sendPixels(PNGImageDecoder.java:531)
at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:452)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:41)
at java.awt.image.Raster.createPackedRaster(Raster.java:458)
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1015)
at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:230)
at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:484)
at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:120)
at sun.awt.image.PNGImageDecoder.sendPixels(PNGImageDecoder.java:531)
at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:452)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:41)
at java.awt.image.Raster.createPackedRaster(Raster.java:458)
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1015)
at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:230)
at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:484)
at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:120)
at sun.awt.image.PNGImageDecoder.sendPixels(PNGImageDecoder.java:531)
at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:452)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
 
  • #6
297
2


Odd. I made one small change for testing on my end and it works. But that's with 3 images. And since it seems you're running out of space, for some reason... Seems to me 113 of those images shouldn't amount to that much memory usage. You could increase the amount of heap space, but you shouldn't have to.

FYI I just hard coded the path to where I put the files (instead of the getResource) to test it with minimal messing around.

I'll try and make a script to duplicate your images so I end up with 113 (a bit later) and see what it does. Perhaps you could see if reducing the number of images you try and show might not help. For example, does it still do that when you set TOTAL_IMAGES to 3?
 
  • #7
297
2


On further reflection, those png images get decompressed and end up much larger in memory. And I believe in Windows the heap memory is set somewhat low by default. Try running it with:

java -Xms128m -Xmx512m LogoAnimator

That might help.
 
  • #8
117
3


I tried removing all the images except the first three that I uploaded, reduced the image count to 3 and get the exact same error.

I can't seem to figure it out. It compiles fine, but throws the error when I try to run it.

Also, I shouldn't be running out of space, total size of 113 images is only 3.93 MB.
 
  • #9
117
3


On further reflection, those png images get decompressed and end up much larger in memory. And I believe in Windows the heap memory is set somewhat low by default. Try running it with:

java -Xms128m -Xmx512m LogoAnimator

That might help.
Where would I put that line of code??
 
  • #10
297
2


I tried removing all the images except the first three that I uploaded, reduced the image count to 3 and get the exact same error.

I can't seem to figure it out. It compiles fine, but throws the error when I try to run it.

Also, I shouldn't be running out of space, total size of 113 images is only 3.93 MB.
Very odd. Works fine with 3 images for me. I notice it does use up quite a lot of heap space on each image. You'd be surprised how large they end up uncompressed. You may need to either (or both) reduce the size of the images to actual icon size, and perhaps use less of them. Of course, increasing heap space as I posted also shouldn't hurt.

I wanted to see how the heap was going after each image load, so I did this (including the previous hard coding of the path to the images):

Code:
      for ( int count = 0; count < images.length; count++ )
      {
         //images[ count ] = new ImageIcon( getClass().getResource(
         //   "images/" + IMAGE_NAME + (count+1) + ".png" ) );
         images[ count ] = new ImageIcon( "/home/XXXXXXXX/TestCode/" +
            IMAGE_NAME + (count+1) + ".png" );
         System.out.println("Heap free: " + Runtime.getRuntime().freeMemory());

      }
That println should give you an idea what's happening with your heap. When it hits 0, kaboom.
 
  • #11
117
3


Ok, not sure where the line of code goes to increase the heap size, so I couldn't do that, but I did go back and reduce the size of the first 3 images drastically. They are now 139 x 138, and I changed the code to run with just the three images, but I still get the same error.
 
  • #12
117
3


Ok, well, now it works a little more. I went back, added the +1 to count once again, and now just am having a problem with the heap space after all, LOL. I don't know how I missed that when I tried earlier. I can go back and resize all the images, but I will still need to increase the heap space because I would like to use the majority of the images if I can.

So exactly where would I put the code to increase the heap space because we have not covered that bit of coding in class and the book is confusing me on this topic.

With the images the staying original size, I can run approx. 70 images without overloading the heap space. If I can increase the heap space I should be able to use all the images.
 
Last edited:
  • #13
297
2


Where would I put that line of code??
That's the command to launch the program. I assume you're using an IDE of some sort? What are you using, Eclipse? If so, do this:
1. Go into the Run menu and select Run Configurations
2. Find the run configuration for your program and select it. Probably under "Java Applications".
3. Go to the "Arguments" tab
4. In the "VM arguments" box, make sure it has "-Xms128m -Xmx512m" in it. Don't mess up the other arguments, of course. Keep spaces between them and so on.

Though I'm confused that it still runs out of heap space with 3 small images and yet your code works fine for me. Only difference is I hard coded the path to the image files.

Don't forget to add that println inside the for loop (add curly braces of course) and see what's happening to your heap space.
 
  • #14
117
3


We are instructed to use NetBeans IDE Version 6.7.1
I will google how to change the heap space for it.
 
  • #15
117
3


Ok, I figured out how to increase the heap, I will toss in a comment for my instructor to let him know he will need to do the same. I finally got it to run properly!

Thank you so much for your help Grep. I also appreciate the tip about increasing heap space, that is sure to come in handy next course when we get into more intense programming.

You have been absolutely AWESOME with all of the help!
 
  • #16
297
2


You're welcome! Glad you got it working.
 

Related Threads on JAVA Animated Logo DUE TODAY HELP!

  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
1
Views
1K
Replies
1
Views
4K
Replies
1
Views
2K
  • Last Post
Replies
4
Views
1K
  • Last Post
Replies
0
Views
4K
  • Last Post
Replies
5
Views
2K
Replies
3
Views
2K
Replies
2
Views
1K
Replies
2
Views
1K
Top