Search code examples
javaarraysswingjoptionpaneimageicon

Presenting random pictures using JOptionPane icon and Math.random


I am taking a programming class, and I have to make an instrument "play". I want to use Math.random to create a random number between either 0-9 or 0-10 and have that number correspond to a picture in an array displayed via JOptionPane icon. My only issue is, how can I create a program that will correspond a random int to a picture and then present it using JOption Pane. Here is what I have so far:

   public static String Flute(String pickYourInstrument, String instrument){
      //try to assign variables to pictures in an array
      ImageIcon icon = new ImageIcon("/home/james/programmingpics/A_Flute");
      JOptionPane.showMessageDialog(null, "A Note", "A Note with Flute", 
      JOptionPane.OK_OPTION, icon);
      for (int i = 0; i < 1000; i++) {
           int random = 1 * (int) (Math.random() * 10);
           System.out.println(random);
      }
   }

I am stuck, I stopped after I realized that I didn't know how to make the ImageIcon icon into an array (I have nine other pictures to make an icon for). Does anyone have an idea how I could create the program?


Solution

  • Simply create an array of ImageIcon, then the random number obtained can be used as an index to that array to get the corresponding icon. Something as simple as

    int randomNumber = //.... get random int
    ImageIcon myIcon = iconArray[randomNumber];