I am trying to load some images into an array for an applet and I know there has to be a better way to do this?
public class Images extends Applet
{
Image card[]=new Image[45];
public void init()
{
img[0]= getImage( getDocumentBase(),"pics/1.gif");
img[1]= getImage( getDocumentBase(),"pics/2.gif");
.....
Even if the filenames aren't predictable based on number, you could still have a collection of them. For example:
// Common prefix removed for brevity
private static final String[] IMAGE_FILES = {
"img1.gif", "happy.gif", "sad.gif" /* etc */
};
Then:
Image[] images = new Image[IMAGE_FILES.length];
for (int i = 0; i < images.length; i++) {
images[i] = getImage(getDocumentBase(), "pics/" + IMAGE_FILES[i]);
}
(There may well be a nicer way of transforming one array into another using a lambda in Java 8 - I haven't checked.)
It's not clear to me that an Images
class is a good idea though - it doesn't really sound like something you'd typically create an instance of. I'd also strongly recommend using private fields.
See more on this question at Stackoverflow