i have a 5x5 Jbutton layout and i m trying to change the color of a Jbutton every time i click a button.
what i m trying to do do is every time a Jbutton is clicked it changes its color and pick a color from this array. this is how i m initializing the buttons with the random colors.
Color[] colors = new Color[4];
//Initialize the values of the array
colors[0] = Color.red;
colors[1] = Color.blue;
colors[2] = Color.yellow;
colors[3] = Color.green;
for(int row=0; row<5; row++) {
for (int col=0; col<5; col++) {
buttons[row][col] = new JButton(buttonLabels[row*5+col]);
buttons[row][col].setLocation(10+col*55, 10+row*55);
buttons[row][col].setSize(50,50);
buttons[row][col].addActionListener(this);
buttons[row][col].setBackground(colors[new Random().nextInt(4)]);
add(buttons[row][col]);
}
}
here is my actionPerfomred method. when i click a button this would give me an error and would do nothing.
public void actionPerformed(ActionEvent e) {
JButton selectedBtn = (JButton) e.getSource();
for (int row = 0; row < buttons.length; row++) {
for (int col = 0; col < buttons[row].length; col++) {
if(index < (colors.length - 1))
{
index++;
}
else
{
index = 0;
}
buttons[row][col].setBackground(colors[index]);
}
}
}
any help on this?