2012-02-06 93 views
0

我正在写一个简单的游戏。我有三个类,第一个是:处理所有涉及到的东西的球,第二个是由一系列“球”组成的游戏,最后一个是包含主线程的窗口。Java - 双缓冲NullPointerException

window.paint调用game.draw以便接收游戏场景的图形。游戏本身加倍缓冲它,以便Image对象可以移动到玩家的球位置(尚未实现)。

所以我的问题,因为我创建一个图像对象,但为什么这初始化为null,因此我得到NullPointerException。

下面是其处理的绘画方法的源:

public class MyWindow extends JFrame { 
     //...the other code 
     public void paint(Graphics g){ 
      thegame.draw(); 
      repaint(); 
     } 
} 

public class Game extends JFrame implements Runnable { 
    ball[] cellmap; 

    //...the other code 

    public void draw(){ 
     Image GameImage = createImage(800,800); 
     Graphics GameGraphics = GameImage.getGraphics(); 

     for(int i = 0;i<cellmap.length;i++) 
      cellmap[i].draw(GameGraphics); 

     g.drawImage(GameImage, 0, 0, this); 
    } 
} 

public class Ball extends JFrame { 
     //...the other code 
    public void draw(Graphics g){ 
     g.setColor(Color.red); 
     g.fillOval((int)(this.x+this.radious),(int)(this.y+this.radious), 
         (int)this.radious,(int)this.radious);   
    } 
} 
+3

请告诉我你不实际使用lowerCamelCase类和UpperCamelCase变量。 – 2012-02-06 17:17:02

+0

可能是相关的:http://stackoverflow.com/questions/1541845/problems-with-createimageint-width-int-height – 2012-02-06 17:18:35

+0

这个代码在引入第二个'JFrame'后就开始出错了,更不用说第三个了!为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。 – 2012-02-06 23:08:27

回答

3

1),请阅读Java Naming Conventions

2)不是好主意,油漆直接到JFrame,把你的画给JComponentJLabelJPanel

3),用于在PaintingSwing使用方法paintComponent,请不是方法paint(Graphics g)draw(Graphics g)

4)如果你想延迟或动画,你画使用javax.swing.Timer

+0

好吧,我不知道有这样的命名约定,所以现在我修好了。我试图使用paintComponent而不是绘画,但我无法弄清楚如何实现它,当我有一个球的阵列,我必须将它们全部绘制。而且,可以在游戏过程中创建球。 – 2012-02-06 18:37:05

+0

@kirill我已编辑你的文章:-) – mKorbel 2012-02-06 18:39:45

+0

我也编辑了我的评论。 – 2012-02-06 18:41:23