How to add an image icon to certain buttons?

I am making a board game and I need to put player 1 and player 2 on a grid of buttons. I use the image icon to represent the part that I want to put on the buttons. The problem is that I have a button loop, and I need to put piece1 on buttons 1,3,5,7,9 and 2 pieces on buttons 2,4,6,8,10.

+3
source share
1 answer

    for(int i=0;i<30;i++){
        buttons[i] = new JButton("label"+ i);
        buttons[i].setBackground(Color.white);
        if (i < 10) {
           if (i%2 == 0) {
             buttons[i].setIcon(piece2);
           } else {
             buttons[i].setIcon(piece1);
           }
        }
        panel.add(buttons[i]);
    }
+3
source

All Articles