Question

I am not sure exactly what I am doing wrong here, I want to create a grid lay out using a Jbutton array, however it is giving me a " null Pointer exception ". Can't seem to find exactly how to place the JButtons on the panel.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GridLayout extends JFrame
{
private final int HEIGHT = 200;
private JPanel panel;
private final int WIDTH = 200;

public GridLayout ()
{
    setTitle( " try this");
    setSize( HEIGHT, WIDTH);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setLayout(new FlowLayout());

    JButton [] but = new JButton [9];

    for(int i = 0; i < 9; i++ )
    {
            but[i]=new JButton();   
    }
    for ( int i = 0; i < 9;i++)
    {
        panel.add(but[i]);
    }

    setVisible(true);
}

public static void main(String[] arg)
{
    new FlowWindow();
}   
}
Was it helpful?

Solution

Where do you create a JPanel object for the panel variable?

Answer: You don't. So change this:

private JPanel panel;

to this:

private JPanel panel = new JPanel();

More importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). You should inspect the line carefully that throws it, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.


As an aside: don't give your classes the same names as important core Java classes. For instance by naming your class GridLayout, you will now have trouble using the java.awt.GridLayout class without completely specifying the class name. You will thus want to change your class name to something else, say MyGridLayout.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top