在Graphics2D上绘制气球

时间:2015-04-25 12:42:49

标签: java graphics2d

我想制作泡泡射击游戏,我在开始时产生气泡有问题。在尝试编译程序时,我遇到错误:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.

public class MyPanel extends JPanel {
    Init init;

    public MyPanel(){
        super();
        init = new Init();      
    }

    public void paint(Graphics g){
        Dimension size = getSize();
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.GRAY);
        g2d.fillRect(0, 0, size.width, size.height - 70);
        for(int j = 0; j < 10; j++)
            for(int i = 0; i < 20; i++){
                init.fields[i][j].b.paint(g);       //here compiler shows error
            }
    }
}


public class Field {
    private int x;
    private int y;
    private int r = 30;
    public Baloon b;


    public Field(int x, int y){
        this.x = x*r;
        this.y = y*r;
    }

    public void addBaloon(int n){
        b = new Baloon(this.x, this.y, r, n);
        }
}

public class Init {

    Parser pr = new Parser();
    private int r = pr.getRadius();
    private int x = pr.getXDimension();
    private int y = pr.getYDimension();
    private int ni = pr.getColorRange();

    Field[][] fields = new Field[x][y];

    private int startX = 20;
    private int startY = 10;

    public Init(){
        for(int yi = 1; yi<y; yi++){
            for (int xi = 1; xi<x; xi++){
                fields[xi][yi] = new Field(xi*r, yi*r);         
            }
        }

        for(int yi = 1; yi < startY; yi ++){
            for(int xi = 1 ; xi < startX; xi++){
                Random rand = new Random();
                int n = rand.nextInt(ni);
                fields[xi][yi].addBaloon(n);    
            }
        }       
    }
}

1 个答案:

答案 0 :(得分:3)

您正在从索引1初始化数组:

for(int yi = 1; yi<y; yi++){
    for (int xi = 1; xi<x; xi++){
        fields[xi][yi] = new Field(xi*r, yi*r);         
    }
}

从0访问它时,如:

for(int j = 0; j < 10; j++)
    for(int i = 0; i < 20; i++){
        init.fields[i][j].b.paint(g);       //here compiler shows error
    }

数组索引从0开始并上升到n-1。所以你需要初始化如下:

for(int yi = 0; yi<y; yi++){
    for (int xi = 0; xi<x; xi++){
        fields[xi][yi] = new Field(xi*r, yi*r);         
    }
}
相关问题