0

I'm trying to make a simple game which i made array of 9 buttons and for loops to display them and add then to ContentPane.

I'm trying to add images to the buttons in the for loops and I cannot get it to work./ any help?

    String[] images = {"rainbow.jpg", "leprechaun.jpg", "potofgold.jpg"}; // IMAGES

    // --- ICONS ---
    Icon Icon1 = new ImageIcon("rainbow.jpg");
    Icon Icon2 = new ImageIcon("leprechaun.jpg");
    Icon Iconwin = new ImageIcon("potofgold2.jpg");
    Icon blank = new ImageIcon("blank.jpg");

    //creates array of buttons called tiles
    JButton[] tile = new JButton[9];

They are the arrays and Icons.

for(int i = 0; i < tile.length; i++)
        {
            contentPane.add(tile[i]);
            tile[i].setIcon(images[1]);
            tile[i].addActionListener(this);
        }

I'm trying to make it random image to the buttons. selects randomly I cannot get it to work I get error on tile[i].setIcon(images[1])

even when trying to just place it the 2nd image it give sme error

method setIcon in class AbstractButton cannot be applied to given types;

            tile[i].setIcon(images[1]);
user3392994
  • 13
  • 1
  • 4

1 Answers1

0

setIcon uses an Icon as its argument rather than a String

tile[i].setIcon(icon1);

Adding the buttons directly would be simpler

getContentPane().add(new ImageIcon(images[i]);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Thanks is there anyway of adding the images using from images[]? I need to add a random image to the buttons , should select 1 random image out of them 3. – user3392994 Oct 31 '14 at 18:17
  • It would be simpler but the assignment wants to be images randomized and this way is the easiest to achieve that. I tried getContentPane().add(new ImageIcon(images[i]); getting no suitable constructor found for ImageIcon(icon) – user3392994 Oct 31 '14 at 18:24
  • To add a random image use the `Random` class to select a `String` from `images` to pass into the `ImageIcon` constructor – Reimeus Oct 31 '14 at 18:27
  • If i just try to tile[i].setIcon(imageIcons[i]); I get errors in cmd after i run it. java.lang.arrayindexoutofboundsexception: 3 at assignmentbk. at assignmentbk.main – user3392994 Oct 31 '14 at 18:28
  • `tile` is an array of length `9` whereas `images` is only `3` in length – Reimeus Oct 31 '14 at 19:59
  • I see that I got it to atleast print out the images onto the buttons but I cannot get them to print out randomly.. on all of the buttons. it just prints on 3 buttons and they are in order.. im using if(e.getSource()==tile[i]) { tile[i].setIcon(imageIcons[i]); // sets IMAGES to buttons } – user3392994 Oct 31 '14 at 20:21