Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Nifty Project Question

+9 votes
I would like to write some code that would show a random image on a graphics object I have created when I click on the object. Is there a way to do this?
asked Oct 26, 2016 in CSC 211 (F16) by Trevor Rogers (100 points)

2 Answers

+2 votes

I did something similar to this in my nifty project, except with imported images. I declared several Strings with the name "images/......jpg" then created a String imageChosen and set that equal to a random number from 1 to the number of images I had. I then had an if/else if to determine which image would be chosen ie:

image1 = "images/.....jpg";
‚Äčif (randomNum == 1) {
    imageChosen = image1;
} else if (randomNum == 2) {
    imageChosen = image2;
} else if (...

Then, whenever I run the program, a random image will be chosen. 

If you're using images drawn using graphics, it would be the same concept, except instead of setting the chosen image equal to a String, you'd draw whichever graphic you wanted in the if statement whenever a specific random number is picked. 

I assume there's an easier way to do this using arrays, but we haven't learned those.. yet.

answered Oct 26, 2016 by Lars Harvey (526 points)
+2 votes

You could name your image files:

image0.jpg
image1.jpg
image2.jpg
image3.jpg
...
image9.jpg

etc, and then in your code you could use:

String randomFileName = "image"+rand.nextInt(10)+".jpg";

to get a random image file name... and then load it with:

BufferedImage randomImage =  panel.loadImage(randomFileName)

answered Oct 27, 2016 by Forrest Stonedahl (3,438 points)
I'm doing something similar to this, but since I'm doing a matching game, I don't want two images appear randomly at the same spot. Is there any way to make sure that two images will not appear at the same spot?
...