0
    // 8x8 shiny button layout
    JButton[][] buttons = new JButton[8][8];
    for (int i=0; i<8; i++) {
        for (int j=0; j<8; j++) {
            buttons[i][j].setLocation(10+j*55, 10+i*55);
            --->buttons[i][j].setSize(69,69);
            int r = 1 + (int)(Math.random()*((7-1)+1));
            buttons[i][j] = new JButton(icons[r]);
            add(buttons[i][j]);

        }

    }

The code above is giving me issue, I keep getting null pointer exception at the code with arrow. I'm new to the forum and java code. Please and thanks for help


I don't know what I did but my code is working now

    // 8x8 shiny button layout
    JButton[][] shinyButton = new JButton[8][8];
    for (int i=0; i<8; i++) {
        for (int j=0; j<8; j++) {
            int r = 1 + (int)(Math.random()*((6-1)+1));
            shinyButton[i][j] = new JButton(icons[r]);
            shinyButton[i][j].setLocation(10+j*69, 10+i*69);
            shinyButton[i][j].setSize(69,69);
            add(shinyButton[i][j]);
        }       
    }
5
  • Can you post the exact error message? Is it happening inside the setSize call? Commented Mar 4, 2014 at 2:38
  • Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at ShinyButtonsView.<init>(ShinyButtonsView.java:22) at ShinyButtonsApp.main(ShinyButtonsApp.java:12) Commented Mar 4, 2014 at 2:41
  • That exception means you forgot to initialize the array. I assumed the array was initialized because the place of the exception was after the setLocation call (which didn't fail). But, that might just be the debugger setting the pointer to the next statement. Commented Mar 4, 2014 at 2:43
  • Isn't buttons[i][j] = new JButton(icons[r]); initializing the array of buttons? Commented Mar 4, 2014 at 3:07
  • Your code is working because you copied the example in the answer below and it initializes individual buttons. The initial array initialization is simply allocating memory for pointers that will point to actual jbutton instances. Commented Mar 4, 2014 at 5:49

1 Answer 1

1

Try to initialize a button first before setting some properties

// 8x8 shiny button layout
JButton[][] buttons = new JButton[8][8];
for (int i=0; i<8; i++) {
    for (int j=0; j<8; j++) {

        /*Initialize a button*/
        int r = 1 + (int)(Math.random()*((7-1)+1));
        buttons[i][j] = new JButton(icons[r]);

        buttons[i][j].setLocation(10+j*55, 10+i*55);
        buttons[i][j].setSize(69,69);      
        add(buttons[i][j]);

    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.