2012-02-06 76 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