0

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?

arsalunic612
  • 129
  • 2
  • 10
  • @FastSnail it gives me an error " Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" and it also gives me a whole bunch of exceptions like "at boardGame.actionPerformed(boardGame.java:82)" – arsalunic612 Mar 14 '16 at 04:04
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Madhawa Priyashantha Mar 14 '16 at 04:06

0 Answers0