I am making a board game and having trouble moving them. The piece will move according to the dice result. Below is what i attempt to do but it does not work.(from button[].addActionListener(new ActionListener()) Note: I have used ImageIcon to represent my pieces. Any help?
//Puts the player 1 piece on button 1,3,5,7,9 and player 2 piece on button 2,4,6,8,10
if ((btnNumber - 1) < 10)
{
if (((btnNumber - 1) % 2) == 0)
{
buttons[btnNumber - 1].setIcon(piece1);
}
else
{
buttons[btnNumber - 1].setIcon(piece2);
}
}
centerPanel.add(buttons[btnNumber - 1]);
}
frame.add(centerPanel, BorderLayout.CENTER);
It looks as though there are some basic things you haven’t quite grasped yet. Here are some suggestions for getting closer to your goal:
button[].addActionListeneris a nonsensical statement. You can’t add an action listener to an entire array at once. Perhaps you meant to saybuttons[btnNumber - 1].addActionListenerand place it inside theforloop.buttons[]==ImageIcon("piece1")is also a meaningless statement (it should not even have compiled). You could trybuttons[btnNumber - 1] == ImageIcon("piece1"), though there is an easier way to do this (#3).piece1Locationandpiece2Locationthat you keep updated as the pieces move. Then you would know instantly where the pieces are, and your logic would simplify toif (btnNumber - 1 == piece1Location)0. The cleanest way to work with an array in Java with aforloop is to start your indexing variable at0as well, and change your comparison from<=to<. With the followingfor(int i = 0; i < 30; i++), you don’t have to keep sayingbtnNumber - 1.