1

I've trouble with a NullPointerException which is the result of

public class Grid extends JFrame {

private JLabel[][] grid;

public Grid(int max) { //from Constructor
    int s = max;
    int v = max;


    Container cont = getContentPane();
    cont.setLayout(new BorderLayout());

    JPanel p1 = new JPanel(new BorderLayout());
    Container content = new JPanel(new GridLayout(s,v)); 

    for (int y = s - 1; y >= 0; y--) {
        for (int x = 0; x < v; x++) {
            grid[x][y] = new JLabel((x)+","+(y));
            content.add(grid[x][y]);
        }
    }

I've tried to reduce the code in this preview a little bit to the important part. The error is caused by

    grid[x][y] = new JLabel((x)+","+(y));

At the end of the day, I want to add an specific amount (max*max) of JLabels to the GridLayout with coordinates in it like the for clauses should give them. Also the here: GridLayout coordinates

Community
  • 1
  • 1

1 Answers1

4

Your array is not initialized, you have to construct the array before assigning values to its elements.

private JLabel[][] grid = new JLabel[MAX][MAX]; 
m.sobolev
  • 261
  • 1
  • 5
  • Thanks for your answer. I think this would be the solution but there's one problem. I can't initialize grid in the Grid class because I need the values given be the Constructor. But when I'm trying to initialize the grid array in the Constructor, eclipse returns 'Illegal modifier for paramter grid; only final is permitted'. I've forgotten to mention that there's a super("Title"); in the Constructor at the beginning, sorry about that! – user3375255 Mar 03 '14 at 21:13
  • If you want to allocate the array in the constructor, does `grid = new JLabel[v][s];` work? – m.sobolev Mar 03 '14 at 21:17
  • 1
    Thanks, now it works! I've declared the array in the Class above the Construcor with 'private JLabel[][] grid;' and then initialized it with 'grid = new JLabel[v][s];' in the Constructor. – user3375255 Mar 03 '14 at 21:27