How to Randomly Cycle Images With Java
You use the Java random number generator to randomly cycle and display images in your Java apps. A list of images used in a form is stored in an array variable. You use the random Java function to randomly choose a number, then use that number to retrieve the image from the array. The random function saves you time with your code, because you do not need to code for the random number generation.
Instructions
-
-
1
Open the Java editor you want to use to create the random image function. Open the Java source code file you want to edit.
-
2
Create an array of images, if you do not already have an image array set up. For instance, the following code creates an array of two images:
string[] images;
images[0] = "image1.jpg";
images[1] = "image2.jpg"; -
-
3
Create a random number you use to plug in to your array. The following code randomly generates a number between zero and one, because the array index starts with zero and not one:
Random gen = new Random();
int number = randomGenerator.nextInt(1); -
4
Display the randomly generated image from the array. The following code shows the image to the user:
System.out.println(images[number]);
-
1