在Graphics2D上绘制气球 [英] Painting balloons on Graphics2D

查看:145
本文介绍了在Graphics2D上绘制气球的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

从0开始访问时,例如:

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
    }

数组索引从0开始到n-1.因此,您需要像这样进行初始化:

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

这篇关于在Graphics2D上绘制气球的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆