从ArrayList添加按钮到JPanel的NullPointerException

时间:2013-12-19 01:11:41

标签: java swing graphics nullpointerexception jpanel

我收到了NullPointerException,我不知道为什么。如果有人可以查看我的代码并告诉我它有什么问题,那就太好了。

提示:构建一个带有输入的按钮金字塔 1)块宽度 2)阻挡高度 3)行号

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


public class BlockPyramidBuilder extends JPanel{

public static int height;
public static int width;
public static int rowNum;
public static JFrame frame = new JFrame();
public static Graphics g;
public static BlockPyramidBuilder test;

public static void main(String[]Args){
    Scanner inputReader = new Scanner(System.in);

    System.out.print("Block Height ------->" );
    height = inputReader.nextInt();
    System.out.print("Block Width ------->" );      
    width = inputReader.nextInt();
    System.out.print("Row Num ------->" );
    rowNum = inputReader.nextInt();

    test = new BlockPyramidBuilder(height, width, rowNum);

    frame.add(test);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

}
public BlockPyramidBuilder(int height, int width, int rowNum){
    ArrayList<MyBox> array = new ArrayList<MyBox>();
    int center = frame.getWidth();
    int x = 0;
    int y = 0;          


    for(int i = 1; i <= rowNum; i++){
        y = height * (i-1);
        for(int j = 1; j <= i; j++){
            x = center + (width/2) * j;
            System.out.println("x: " + x + "      y: " + y);

            MyBox r = new MyBox(x, y, width, height);
            array.add(r);
        }
    }
    for(int i = 0; i < array.size(); i++){
        test.add(array.get(i));
    }

}

}
class MyBox extends JButton{
public MyBox(int x, int y, int height, int width){
    super();
    setBackground(new java.awt.Color(37, 80, 130));
    setFont(new java.awt.Font("Trebuchet MS", 0, 24));
    setForeground(new java.awt.Color(38,38,38));
    setSize(height, width);
    setLocation(x, y);

}
}

代码获取正确的坐标以绘制框,但是将MyBox添加到JPanel时出错。另外,我想知道

2 个答案:

答案 0 :(得分:1)

在构造函数BlockPyramidBuilder中,引用在构造函数完成之前未设置的测试对象。<​​/ p>

答案 1 :(得分:1)

在调用构造函数之前未初始化

test,并尝试在构造函数中使用它。因此,您获得NullPointerException

此外,您不应该声明所有这些变量static。你有一个类,它应该有实例变量。