Search code examples
javaarraysswingjbuttonimageicon

fill a 2-dimensional JButton Array with different images


I am working on a small easter egg in my game, this is how it looks. If the player clicks a specific button 5 times, every button that is not black get's a different picture. So far I managed to make it look like this where every Button has the same picture.

The code for the image and change every button's image is this:

BufferedImage img = ImageIO.read(new File("kronk/18.png"));

for (int i = 0; i < buttons.length; i++) { //Goes one time through the complete Array
    for (int j = 0; j < buttons[i].length; j++) {

        if(buttons[i][j].getBackground() != Color.black) {
            buttons[i][j].setText("");
            buttons[i][j].setIcon(new ImageIcon(img));
        }
    }
}

The code so far is hardcoded to always display 18.png

The images are stored in a folder which looks like this, where 1.png goes on Button 1, 2.png goes to 2, etc...

What would be the best way to fill every button with it's corresponding image?


Solution

  • Try this:

    for (int i = 0; i < buttons.length; i++) { //Goes one time through the complete Array
        for (int j = 0; j < buttons[i].length; j++) {
            if(buttons[i][j].getBackground() != Color.black) {
                BufferedImage img = ImageIO.read(new File("kronk/"+(i*5 + j + 1)+".png"));
                buttons[i][j].setText("");
                buttons[i][j].setIcon(new ImageIcon(img));
            }
        }
    }
    

    As you have a 5x5 array i*5 + j will give you the elemnts count from 0 to 24. But since the enumeration of your pictures starts with one you have to add one at the end i*5 + j + 1