Question

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

Was it helpful?

Solution

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

private JLabel[][] grid = new JLabel[MAX][MAX]; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top