1

I am making an applet that displays a random collection of 10 cards based upon 10 random integers.

My idea was to make an array of the 52 displayable cards (not including jokers) and display each cards from the array based upon the random integer like this (sorry i don't know how to use code blocks):

for (int i = 0; i<cards.length; i++) { //cards being my image array
     //code that displays each image
}

But I ran into trouble trying to add images into the array and I don't know how to display the images from the array either.

Should I be adding them like this:

Image[] cards = new Image[52];
cards[0] = c1;   //name of the Ace of Clubs, I had used getImage() to already get it

The preceding statements throw up errors saying it's an illegal start.

I also need help with displaying the images once I incorporate the images since I don't think:

System.out.println(cards[x]);

Will work with images.

Thanks in advance and sorry for seeming so complicated, I've tried to water it down as much as possible!

2
  • Why not use an array of Strings and load in the paths of the images? When you do your displaying, just use the path in the array to load and then display the image. Commented Oct 7, 2012 at 23:19
  • 2
    Why not use a java.util.List implementation, such as java.util.ArrayList? Commented Oct 7, 2012 at 23:23

1 Answer 1

1

So, here's my silly take on it...

enter image description here

public class RandomCards {
    public static void main(String[] args) {
        new RandomCards();
    }

    public RandomCards() {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {

                try {
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new RandomCardsPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }

            }

        });

    }

    public class RandomCardsPane extends JPanel {

        // A list is a collection of Image objects...
        private List<Image> cardList;
        private Image card = null;

        public RandomCardsPane() throws IOException {

            // My cards are stored in the default execution location of the program
            // and are named "Card_1.png" through "Card_51.png"...
            // You image loading process will be different, replace it here..

            // ArrayList is a dynamic list (meaning it can grow and shrink
            // over the life time of the list) and is backed by an array
            // which shouldn't concern you, the only thing you really need to
            // know is that it has excellent random access...
            cardList = new ArrayList<Image>(51);
            for (int index = 0; index < 51; index++) {
                cardList.add(ImageIO.read(new File("Card_" + index + ".png")));
            }

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    card = cardList.get(Math.min((int)Math.round(Math.random() * cardList.size()), 51));
                    repaint();
                }
            });
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            if (card != null) {
                int x = (getWidth() - card.getWidth(this)) / 2;
                int y = (getHeight() - card.getHeight(this)) / 2;
                g.drawImage(card, x, y, this);
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(225, 315);
        }
    }
}

I would also prefer ImageIO over Toolkit.getImage or even ImageIcon, apart from the fact that it guarantees the image data is loaded BEFORE the method returns, it also supports a greater number of image formats and is extendable via plugins...

Sign up to request clarification or add additional context in comments.

6 Comments

AFAIU image readers are a Service Provider Interface I that is either available for all J2SE image loading methods or none. So when you say "ImageIO ..it also supports a greater number of image formats and is extendable via plugins..." I think that is misleading. If you add an SPI for TIFF, ImageIO as well as the other methods will be able to read TIFFs. OTOH if the default include JPG, GIF, PNG & BMP, then they will all be able to load those types.
Thanks, this is a little out of my over the range of java that I have learned (just a novice here) but I get the general idea of it (and I'll definitely have to research the ArrayList thing because I've heard of it alot but never found out what it is).
@Timo An ArrayList is a dynamic array. Essentially that means you can "think" of it as an array, but it can change size over time, without you needing to do anything special (like reallocate space, copy the contents etc).
Oh... how did I not learn about this earlier, it seems much more flexible and easier than creating arrays with pre-specified sizes. Thanks!
Sorry to be getting back to you so late! I've bee working with ArrayLists now and I've come across this error: "unsafe or unchecked operations for arraylist" for lines: <object>.add(<value>); apparently it says "E is a type variable"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.