I am trying to change the color of every button EXCEPT the button clicked. This code works if I change it to only the button clicked changing its color. However, when I change the to the desired result I get a java.lang.NullPointerException
error. New To Java not sure how to tackle these errors. Thanks.
public class Hw2 {
static JButton buttons[] = new JButton[8];
static Random rand = new Random();
public static void main(String[] args) {
//deleted non useful code
for(JButton button: buttons) {
button = new JButton("Click Me");
button.setBounds(0,0,50,50); //initialize and set bounds
button.setOpaque(true); //show color and randomly pick
button.setBackground(new Color(rand.nextInt(256),
rand.nextInt(256),
rand.nextInt(256)));
button.setBorderPainted(false);
AnotherHandler bh =new AnotherHandler(button); // add event listener
button.addActionListener(bh);
panel.add(button);
}
}
static class AnotherHandler implements ActionListener{
JButton button;
AnotherHandler(JButton buttonP){
button=buttonP;
}
@Override
public void actionPerformed(ActionEvent e) {
for (JButton but : buttons) {
but.setBackground(new Color(rand.nextInt(256),
rand.nextInt(256),
rand.nextInt(256)));
}
}
}
}