java - 在 Graphics2D 上绘制气球

标签 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 初始化数组:

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);         
    }
}

关于java - 在 Graphics2D 上绘制气球,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29865305/

相关文章:

java - 找不到 Open Liberty 19.0.0.7 batchManagement-1.0 功能部件

java - 修改FileInputStream(文件的某些部分)

java - 如何绘制指定半径的圆和矩形?

ios - 使用iOS 4.2的iPhone 3G的图像大小限制是多少?

java - 如何查看 Graphics2D 中的某些内容是否超出框架

java - 如何通过代理从 HTTPS Url 获取数据?

java - 为什么 java 在...复杂时返回 java.util.LinkedHashMap

java - 如何使用 JAVA High Level Rest Client 获取索引中存在的文档总数

java - 如何将事件添加到复选框?

java - 如何在 - Graphics2D 中使像素完美的 Line2D