-
What am I doing wrong?
I'm trying to learn Java and am having problems with a simple applet I am authoring, the purpose of this simple applet is to flip through images passed to the applet as parameters every few seconds. Everything compiles fine but when I try to run it through the appletviewer I get a NullPointerException on the boldface line below...
Code:
import java.awt.*;
import java.applet.*;
import java.util.*;
public class ImageFlip extends Applet
{
private Image imgs[];
private int numimgs = 0;
private int curimg = 0;
public void init()
{
String name;
for(numimgs = 0; (name = getParameter("img" + numimgs)) != null; ++numimgs);
{
imgs[numimgs] = getImage(getDocumentBase(), name);
}
}
public void start()
{
while(this.isActive() == true);
{
paint(getGraphics());
wait(1000);
}
}
private void wait(int millisecs)
{
Date dt = new Date();
long strt;
strt = dt.getTime();
while(dt.getTime() - strt < millisecs) {}
}
public void paint(Graphics g)
{
g.drawImage(imgs[++curimg], 0, 0, 500, 400, this);
if((curimg + 1) >= numimgs) {curimg = 0;}
}
}
-
nothing is wrong with the line you have, i would check your bounds of your for loop, put a system.out.println in there dumping the loop iterator (numings). I think you will probably find that you are off by 1.
-
thanks for replying billrogers but the array of Image objects has no bounds I am trying to use a dynamic array so that I can load as many objects as is specified in the applet parameters. I'm almost positive that I am doing the redimensioning of the array wrong the book I am using as a reference doesn't really go very deep into array's so it is no help.
-
I didnt say you had a problem with the bounds of your array, I said you have a problem with your loop bound. What I believe is happening is your loop (for) is not acting as should, maybe trying to load an extra image which you are not supplying. Thus when the getImage goes to run, there is no file, thus returning a null pointer exception, check the getImage api, I believe if I remember right it will return null pointer exception in this case.
-
You need to instantiate the images similar to this:
Code:
public Image[] img = new Image[size];
Then do a for loop and set the image sources.