Painting balloons on Graphics2D

泄露秘密 提交于 2020-02-05 13:56:45

问题


I want to make bubble shooter game and I have problem with generate bubbles at start. When trying to compile program, I have error: 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:


You are initializing array from index 1:

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

While accessing it from 0 like:

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
    }

Array index starts from 0 and goes upto n-1. So you need to initialize like:

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


来源:https://stackoverflow.com/questions/29865305/painting-balloons-on-graphics2d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!