我正在编写类似于Atari Breakout的程序。因此,我正在创建一个ArrayList<Rect>。代码是:

package spiel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JFrame;
import shapes.Rect;

public class Spiel extends JFrame implements ActionListener
{
    Spiel()
    {
        super("Bounce Game");
    }

    static Spiel spiel = new Spiel();
    static ArrayList<Rect> rects = new ArrayList<Rect>();

    private static final long serialVersionUID = 2L;

    public  void drawRects()
    {
        Graphics Stift = getGraphics();
        for(int i = 0; i <= 14; i++)
        {
            Stift.drawRect(rects.get(i).hoch, rects.get(i).breit, rects.get(i).punktx, rects.get(i).punkty);
        }
    }

    public static void main(String[] args)
    {
        Spiel frame = new Spiel();
        frame.setSize(1200,1000);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        for(int i = 0; i<=14; i++)
        {
            int h = 0;
            int b = 0;
            if(i <= 4) h =0;
            if(i <= 9) h =1;
            if(i <= 14)h =2;

            if(i <= 4) b =i;
            if(i <= 9) b =i-5;
            if(i <= 14)b =i-10;

            rects.add(new Rect(100, 200, 0+h*100, 0+b*200));
            spiel.drawRects();
        }
    }

    public void actionPerformed(ActionEvent arg0)
    {
    }
}


Rect类包含:

package shapes;

import java.awt.Rectangle;

public class Rect extends Rectangle {
    private static final long serialVersionUID = 1L;
    public int hoch;
    public int breit;
    public int punktx;
    public int punkty;

    public Rect(int h, int b, int x, int y)
    {
        this.hoch = h;
        this.breit = b;
        this.punktx = x;
        this.punkty = y;
    }
}


但是当我调用NullPointerExceptionget(i)时得到一个drawRects(),我不知道为什么。

最佳答案

看这行:

for(int i = 0; i <= 14; i++)


你要:

for(int i = 0; i < rects.size(); i++)


这是因为您仍在创建rects时调用了drawRects方法-因此,第一次调用它时,您将只有1个rect,当然不是15。尝试在初始化框架之前定义将要使用的所有内容。或任何UI元素。

09-27 18:32