TheUnicornCow
TheUnicornCow

Reputation: 49

how to create an array of images in java?

I am trying to initialise a deck of cards, and display them (I have the images in .gif). The only problem I've encountered is initialising the deck itself. So far, I've tried to create four arrays (one for each suit) as such:

import java.applet.*;
import java.awt.*;

public class deckOfCards extends Applet
{
    public void init()
    {
        image clubs = new image[13];
        image hearts = new image[13];
        image spades = new image[13];
        image diamonds = new image[13];
    }
}

and then do something like this for each suit:

for( int i = 0; i <= 13; i++ )
{
    clubs[i] = getImage( getDocumentBase(), c(i).gif )
}

(the card files are saved in filenames c1.gif, c2.gif.....c13.gif for each suit)

I get an error saying that symbol "image" can't be found, but doesn't java.awt.image have a class to create the image object and image methods?

Upvotes: 4

Views: 42863

Answers (2)

Reimeus
Reimeus

Reputation: 159784

image is not a valid class in the AWT package, make the first letter uppercase.

You have some syntax issues:

  • Capital I in Image
  • Missing left-hand-side array brackets
  • Don't go beyond the index of your Image array when looping
  • Quotes needed for getImage call

Java naming conventions indicate that classes start with a capital letter, so too should your class:

public class DeckOfCards extends Applet {

    public void init() {

       Image[] clubs = new Image[13];
       for (int i = 0; i < clubs.length; i++ ) {
            clubs[i] = getImage( getDocumentBase(), "c" + (i + 1) + ".gif");
        }
        ...
    }
}

Also Applet is a museum piece and has been superseded by the lightweight javax.swing.JApplet.

Upvotes: 8

Ariel Grabijas
Ariel Grabijas

Reputation: 1512

Thats the way you do it using ArrayList Containter. In practice ArrayList is.. an array, but much more flexible.

ArrayList<Image> arrayName = new ArrayList<Image>();
Image imageName = getImage(getCodeBase(),"direction.jpg");
arrayName.add(imageName);

Upvotes: 1

Related Questions