2016-10-19 44 views
-1

我收到一個錯誤:圖形g上的java.lang.NullPointerException。 這是我的代碼:我收到一個錯誤:圖形g上的java.lang.NullPointerException g

package main; 
import java.awt.Canvas; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.image.BufferStrategy; 
import javax.swing.JFrame; 
public class main implements Runnable { 
public static final int WIDTH = 1024; 
public static final int HEIGHT = 1024; 
public static final String TITLE = "platformer"; 
public boolean running = false; 
static main home = new main(); 
public Graphics g; 
public static Canvas canvas = new Canvas(); 
public static void main(String[] args) { 
    home.display(); 
    home.start(); 
} 
public void display(){ 
    JFrame frame = new JFrame(TITLE); 
    frame.setSize(WIDTH, HEIGHT); 
    frame.setResizable(false); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
    canvas.setPreferredSize(new Dimension(WIDTH, HEIGHT)); 
    frame.add(canvas); 
} 
BufferStrategy bs; 
public void render(){ 
    bs = main.getCanvas().getBufferStrategy(); 
    if(bs == null){ 
     main.getCanvas().createBufferStrategy(3); 
    } 
    g = bs.getDrawGraphics(); 
    g.fillRect(0, 0, WIDTH, HEIGHT); 
    g.dispose(); 
    bs.show(); 
} 
public void tick(){ 

} 
public void run(){ 
    long lastTime = System.nanoTime(); 
    final double amountofticks = 60; 
    double ns = 1000000000/amountofticks; 
    double delta = 0; 
    double time = 0; 
    int frames = 0; 
    while(running){ 
     long now = System.nanoTime(); 
     delta += (now-lastTime)/ns; 
     time += (now-lastTime); 
     lastTime = now; 
     if(delta>=1){ 
      home.tick(); 
      home.render(); 
      delta--; 
      frames++; 
     } 
     if(time>1000000000){ 
      System.out.println(frames); 
      time = 0; 
      frames = 0; 
     } 
    } 
    stop(); 
} 
private Thread thread; 
public void start(){ 
    running = true; 
    thread = new Thread(this); 
    thread.start(); 
} 
public static Canvas getCanvas(){ 
    return canvas; 
} 
public void stop(){ 
    try { 
     thread.join(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 
} 

我收到錯誤消息: 異常在線程 「線程2」 main.main.render顯示java.lang.NullPointerException (main.java:37) 在main.main.run(main.java:59) at java.lang.Thread.run(Unknown Source) line 37 is g = bs.getDrawGraphics(); 我認爲由於某種原因圖形爲空。 我試圖讓這段代碼很長一段時間

+2

對於神智的目的,請不要再包稱爲'main',或類稱爲'主要「,因爲它變得非常難以解釋。 – Compass

+1

請學習如何正確縮進代碼。如果它在源文件中縮進,那麼當你複製/粘貼到堆棧溢出時,選中它並按下CTRL + K –

回答

1

行更改

main.getCanvas().createBufferStrategy(3); 

bs = main.getCanvas().createBufferStrategy(3); 
+0

我在該行上收到一個錯誤,一旦我改變它: –

+0

類型不匹配:無法從無效BufferStrategy –

+0

就行了我改變即時通訊獲取錯誤:類型不匹配:無法從void轉換爲BufferStrategy –