我想创建对象的二维数组,但无论我如何创建它,我都会得到空指针异常。我应该如何制作对象数组来让它们工作?这里是我的代码:对象数组 - 空指针异常
Game.java package com.jakob.game1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Canvas;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferStrategy;
import java.util.Random;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable, MouseMotionListener{
private static final long serialVersionUID = 1L;
public static final int gHeigh = 500;
public static final int gWidth = 500;
public static final int tHeigh = gHeigh/5;
public static final int tWidth = gWidth/5;
private boolean running;
public Random random;
public BufferStrategy b;
public Graphics g;
public Image bi;
public Pixel[][] pixel = new Pixel[tHeigh][tWidth];
private void start(){
running = true;
new Thread(this).start();
}
public static void main(String args[]){
Game game = new Game();
JFrame frame = new JFrame("Game test");
frame.setLayout(new BorderLayout());
frame.setBounds(0, 0, gHeigh, gWidth);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game, BorderLayout.CENTER);
//frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
public void run() {
bi = createImage(gHeigh, gWidth);
g = bi.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, gHeigh, gWidth);
g.setColor(Color.white);
addMouseMotionListener(this);
for(int i=0; i<tHeigh; i++){
for(int j=0; j<tWidth; j++){
if(pixel == null){
pixel[i][j] = new Pixel; //No matter what I write here it can't create this
}
}
}
if(pixel != null){
for(int i=0; i<tHeigh; i++){
for(int j=0; j<tWidth; j++){
pixel[i][j].setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
}
}
}
while(running){
for(int i=0; i<tHeigh ;i++){
for(int j=0; j<tWidth; j++){
paint(g, i*5, j*5);
}
}
}
}
public void paint(Graphics g, int x, int y){
g.setColor(pixel[x][y].getColor());
g.fillRect(x, y, 5, 5);
}
public void mouseDragged(MouseEvent e) {
g.fillRect(e.getX()-2, e.getY()-2, 4, 4);
repaint();
e.consume();
}
public void mouseMoved(MouseEvent e) {
}
public void update(Graphics g) {
g.drawImage(bi, 0, 0, this);
}
public void paint(Graphics g) {
update(g);
}
}
Pixel.java
package com.jakob.game1;
import java.awt.Color;
public class Pixel {
private Color color;
public Pixel(){
color = new Color(0,0,0);
}
public void setColor(Color color){
this.color = color;
}
public Color getColor(){
return this.color;
}
}
堆栈跟踪在哪里? – 2012-02-28 09:56:53