0

I am just a doing a little project on my own, trying to create a bingo game. I'm wondering why I'm getting a nullpointer when trying to set the text of a JLabel. The only thing the JLabel needs to display is a random number 1-15.

static JLabel[] boardNumbers = new JLabel[25];
static Random r = new Random();

 public static void generateBoard() {

    for (int i = 0; i < 1; i++) {
        if (i < 5) {
            int n = r.nextInt(15);
            numbersUsed[i] = n;
            boardNumbers[i].setText("" + n);
        } else if (i >= 5 && i < 10) {
            //i numbers
        } else if (i >= 10 && i < 15) {
            //n numbers
        } else if (i >= 15 && i < 20) {
            //g numbers
        } else {
            //o numbers
        }
    }

}

The line that is giving me a nullpointer is this line boardNumbers[i].setText("" + n);

For the full source code you can view this: https://github.com/charlieSplittstoser/Bingo/blob/master/Bing0/src/Main.java

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Charlie
  • 90
  • 9
  • 1
    initialize the elements of the array before using them – Reimeus Jan 10 '16 at 22:55
  • When you make a new array like `new JLabel[25]`, it is empty and contains only nulls. The first thing you should do in that `for` loop is initialize the array element with a new JLabel. – markspace Jan 10 '16 at 22:55
  • `static JLabel[] boardNumbers = new JLabel[25];` creates an array of 25 elements which are `null`, you need to fill this array with instances of `JLabel`. Also, please, learn to deal without `static` – MadProgrammer Jan 10 '16 at 22:56
  • Eclipse was yelling at me because they were not static. Also, how do I fill those instances? I thought thats what I was doing by adding text to it. – Charlie Jan 10 '16 at 22:58
  • @Chawbee Then you have a design problem, `static` is not a good way to design your code, you need to learn a better way achieve your results. It's not that you should NEVER use `static`, but you need to learn when it's use is appropriate. Over use of `static` is one of the biggest causes for problems in the questions we see here on SO – MadProgrammer Jan 10 '16 at 23:02
  • @MadProgrammer Yeah I'm a beginner to this. I don't know a way around it yet. Also how do I fill the instances of the array? – Charlie Jan 10 '16 at 23:03
  • 2
    Use a `for-loop`, loop over the array and create a new `JLabel` for each element in the array – MadProgrammer Jan 10 '16 at 23:11
  • @MadProgrammer Thank you very much. It is now working :) The reason everything is static in the program is because I am placing the generateBoard() method the main method (public static void main(String[] args) ) . It says anything used in the method needs to be static. Is there a different way to launch generateBoard() upon the start of the program without putting it in the main method? – Charlie Jan 10 '16 at 23:19
  • Use a class instance instead and call it's methods – MadProgrammer Jan 10 '16 at 23:20

0 Answers0