我一直在关注Java Game Programming for Beginners教程系列,并希望通过应用背景图像来进行实验。不幸的是,当我通过该paintComponent
方法渲染它时,它会随着我的精灵移动(尽管连续一个单位而不是五个);当我通过paint方法渲染它时,我得到一个奇怪的闪烁框,它与setBackground (color)
属性中指定的颜色相匹配,JFrame
并且它与精灵一起移动,与前一个实例的精灵相同(在 内paintComponent
)。
我如何编码图像以保持静态,作为背景应该是?
代码:
public class JavaGame extends JFrame{
int x, y;
private Image dbImage;
private Graphics dbg;
Image ghost;
Image bg;
public class AL extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == e.VK_LEFT){
if(x <= 8)
x = 8;
else
x += -5;
}
if(keyCode == e.VK_RIGHT){
if(x >= 235)
x = 235;
else
x += +5;
}
if(keyCode == e.VK_UP){
if(y <= 18)
y = 18;
else
y += -5;
}
if(keyCode == e.VK_DOWN){
if(y >= 235)
y = 235;
else
y += +5;
}
}
public void keyReleased(KeyEvent e){
}
}
public JavaGame(){
//Load images
ImageIcon i = new ImageIcon("C:/Users/Taylor/workspace/Java game/src/ghost.png");
ghost = i.getImage();
ImageIcon j = new ImageIcon("C:/Users/Taylor/workspace/Java game/src/bg.png");
bg = j.getImage();
//Game properties
addKeyListener(new AL());
setTitle("Java Game");
setSize(500, 500);
setResizable(false);
setVisible(true);
setBackground(Color.GRAY);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 150;
y = 150;
}
public void paint(Graphics g){
g.drawImage(bg, 0, 0, null);
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, x, y, this);
}
public void paintComponent(Graphics g){
g.setColor(Color.WHITE);
g.drawImage(ghost, x, y, this);
repaint();
}
public static void main(String[] args) {
new JavaGame();
}
图片: