Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create an array of images in java?

Tags:

java

arrays

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?

like image 339
TheUnicornCow Avatar asked Jan 15 '23 09:01

TheUnicornCow


2 Answers

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.

like image 75
Reimeus Avatar answered Jan 16 '23 23:01

Reimeus


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);
like image 30
Ariel Grabijas Avatar answered Jan 16 '23 23:01

Ariel Grabijas