0

I am trying to get the separate RGB components from each element in a 2D color array,but it keeps throwing a NullPointerException and I am not sure why.

CODE:

    Color[][] grid = new Color[MaxColors][MaxColors];

    int R1 = 0;


    for(int x = 0; x < N; x++){
        for(int y = 0; y < N; y++){


            R1 = grid[x][y].getRed(); 
            /* do something with R1*/



        }
    }

I also tried to first add the colors to a list and and then convert it to a one-dimensional array. But I still get the same error.

    List<Color> colorList = new ArrayList<Color>();

    for(int x = 0; x < N; x++){
        for(int y = 0; y < N; y++){


            colorList.add(grid[x][y]);

        }
    }

    Color[] SortColors = colorList.toArray(new Color[colorList.size()]);       

    for(int x = 0; x < SortColors.length; x++){

        R1 = SortColors[x].getRed();
       System.out.print(" " + SortColors[x]);
       System.out.print(" " + R1);

    }

It prints the following:

java.awt.Color[r=98,g=85,b=217] 98 java.awt.Color[r=254,g=110,b=177] 254Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at DrawGrid.ColourSorting.sortColours(ColourSorting.java:43)
gnat
  • 6,213
  • 108
  • 53
  • 73
CMalan
  • 13
  • 1
  • 5
  • 1
    What's N? Show all relevant code please. –  Feb 26 '15 at 13:39
  • 1
    You should post all of your code. Reading the first code block I'd say the colors are not initialised. You've just created an empty two-dimensional array. When you iterate over the array all the buckets are `null`. Calling `getRed()` on `null` obviously will result in a `NullPointerException` ... – Jens Feb 26 '15 at 13:45
  • Also the expeception occurs at `DrawGrid.ColourSorting.sortColours(ColourSorting.java:43)`. What is `sortColours`? – ryanyuyu Feb 26 '15 at 13:46
  • Thank you all for your response! N is the size of the input array. I receive the the 2D color array from another class: public List sortColours(Color[][] a) and N = a.length. I then copy this into my grid array. – CMalan Feb 27 '15 at 11:12
  • However I found my mistake. Thanks for pointing that out Jens. I had empty blocks in my colour grid, which obviously equals null. So every time it tries to access an empty block it throws the NullPointerException. So I just added an If statement . if(grid[x][y] != null){R1 = grid[x][y].getRed()} else R1 = 0. – CMalan Feb 27 '15 at 11:15

0 Answers0