0

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)));
            }
        }
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Anon211
  • 27
  • 7
  • 2
    Your array is empty. Defining an array does NOT create 8 JButton objects. You need to use: `for (int i =0; i < buttons.size(); i++)` as your for loop. – camickr Mar 07 '21 at 23:01
  • Genius! Thank You! I just have a question though, how did it render the buttons prior? It was even capable of changing the color of the button that was clicked. – Anon211 Mar 07 '21 at 23:08
  • 2
    1) *"not sure how to tackle these errors"* See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) 2) Based on the title, I'd suggest instead using a group of `JRadioButton` components in a `ButtonGroup`. The selected and unselected icons of each button can be set to different colored icons when they are constructed. All the rest will be handled automatically. – Andrew Thompson Mar 07 '21 at 23:26
  • 1
    @Anon211 , *how did it render the buttons prior?* - It didn't. You somehow changed the code. – camickr Mar 08 '21 at 01:03

0 Answers0