在下面的代码中,我使用 doubleBuffer 来避免图像闪烁,正如我的这个问题中所建议的那样
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestProgram extends JFrame implements KeyListener {
private Image doubleBuffer;
private Graphics myGraphics;
private BufferedImage TestImage;
private int cordX = 100;
private int cordY = 100;
public TestProgram() {
setTitle("Testing....");
setSize(500,500);
imageLoader();
setVisible(true);
}
public static void main(String[] args) {
new TestProgram();
}
public void imageLoader() {
try {
String testPath = "test.png";
TestImage = ImageIO.read(getClass().getResourceAsStream(testPath));
} catch (IOException ex) {
ex.printStackTrace();
}
addKeyListener(this);
doubleBuffer = createImage(getWidth(), getHeight());
myGraphics = doubleBuffer.getGraphics();
drawImages();
}
@Override
public void update(Graphics g) {
drawImages();
g.drawImage(doubleBuffer, 0, 0, this);
}
public void drawImages() {
myGraphics.drawImage(TestImage, cordX, cordY, this);
}
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_RIGHT: {
cordX+=5;
}
break;
case KeyEvent.VK_LEFT: {
cordX-=5;
}
break;
case KeyEvent.VK_DOWN: {
cordY+=5;
}
break;
case KeyEvent.VK_UP: {
cordY-=3;
}
break;
}
repaint();
}
public void keyTyped(KeyEvent ke) {}
public void keyReleased(KeyEvent ke) {}
}
问题是我在这一行得到了一个 nullPointerException
myGraphics = doubleBuffer.getGraphics();
我这样做的方法是否正确?请帮忙。谢谢