在尝试加倍缓冲区时,我遇到了一个异常:java.lang.NullPointerException。我意识到这意味着指针什么也没看,因此“ g.drawImage(backBuffer,0,0,this);” (引发异常的区域)不能执行任何操作。但是,浏览完所有内容后,我没有为任何事情分配空值……也许我没有正确使用Graphics对象,但是我做了相当多的研究但无济于事:How do you double buffer in java for a game? and < / em> http://compsci.ca/v3/viewtopic.php?t=25991。对于背景,这是针对使用.png作为背景,子画面等的游戏。而且我确实知道如何实际绘制png只是它遇到的双重缓冲。
package wows;
import java.awt.*;
import java.awt.image.*;
import java.text.AttributedCharacterIterator;
import javax.imageio.*;
class WoWS extends JPanel{
public static BufferedImage greenSlime;
public WoWS () {
super();
try {
greenSlime = ImageIO.read(new File ("C:\\Users\\NAME\\Documents\\NetBeansProjects\\WoWS\\src\\imageBank\\Green_Slime.png"));
} catch (IOException e) {System.out.println("Sprites failed to load...");}
}
static class Entity{
String AIType = null;
int xc = -1;
int yc = -1;
String SpriteSet = null;
int Mh = -1;
int Ch = -1;
int Dmg = -1;
String EffectList = null;
int hitRad = -1;
public Entity () {} //constructor
void cleanSlate() {
String AIType = null;
int xc = -1;
int yc = -1;
String SpriteSet = null;
int Mh = -1;
int Ch = -1;
int Dmg = -1;
String EffectList = null;
int hitRad = -1;
} //effectively wipes the whole entity to be created anew//
void genEntity(String AI, int x, int y, String Sprite, int M, int C, int D, String Effect, int hitbox) {
AI = this.AIType;
x = this.xc;
y = this.yc;
Sprite = this.SpriteSet;
M = this.Mh;
C = this.Ch;
D = this.Dmg;
Effect = this.EffectList;
hitbox = this.hitRad;
} //creates anew
}
public static void main(String[] args){
WoWS game = new WoWS();
game.run();
System.exit(0);
}
public void run() {
initialize();
draw();
while (isRunning) {
long time = System.currentTimeMillis();
time = (1000/fps) - (System.currentTimeMillis() - time);
//game loop logic goes under here//
//playerIn();
//entityLog();
//draw();
if (time > 0) {
try{Thread.sleep(time);
}catch(Exception e) {}
} else if (fps == 60){System.out.println("Falling Behind!");fps = 30;}
}
}
boolean isRunning = true; int fps = 60; //variables
public void initialize() {
JFrame f = new JFrame("Window");
f.add(new WoWS());
f.setResizable(false);
f.setSize(1900, 1000);
f.setBackground(Color.BLACK);
f.setVisible(true);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setTitle("The Wizard of West Street"); //JFrame logic
Entity E1 = new Entity();Entity E2 = new Entity();Entity E3 = new Entity();Entity E4 = new Entity();Entity E5 = new Entity();Entity E6 = new Entity();
}
public void draw() {
BufferedImage backBuffer = new BufferedImage(1900,1000,BufferedImage.TYPE_INT_RGB);
Graphics g = getGraphics();
Graphics bg = backBuffer.getGraphics();
bg.setColor(Color.WHITE);
bg.fillRect(0,0,500,500);
bg.setColor(Color.RED);
bg.fillOval(100,100,200,200);
paint(bg);
g.drawImage(backBuffer, 0, 0, this);
} }