我在跨JFrame
窗口移动图像时遇到了一些问题。以下是代码的外观:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class Main extends JFrame implements KeyListener{
Image caitlanImage = new ImageIcon("Caitlan.png").getImage();
Person caitlan = new Person(caitlanImage, "Caitlan", 10, 200, true);
Person jake;
Image jakeImage;
//Background images
Image granadaBackground;
public static void main(String[] args) throws InterruptedException{
new Main();
}
public Main() throws InterruptedException{
setSize(700,300);
setTitle("Project Anniversary");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addKeyListener(this);
//Instantiate background images
granadaBackground = new ImageIcon("Granada Background.jpg").getImage();
//Spawn first background
spawnBackground(granadaBackground);
//Spawn initial sprite
spawnSprite(caitlan);
}
public void moveSprite(Person p) throws InterruptedException{ //Method to move a
sprite 10 pixels (BROKEN)
Graphics g = this.getGraphics();
p.setLocation(p.getPosX() + 10, p.getPosY());
g.drawImage(caitlan.getImage(), caitlan.getPosX() + 10,
caitlan.getPosY(), caitlan.getImage().getWidth(null), caitlan.getImage().getHeight(null),
null);
}
public void paint(Graphics g){ //Overridden paint method
}
public void spawnSprite(Person p){ //Method to initially spawn a sprite
Graphics g = this.getGraphics();
g.drawImage(p.getImage(), p.getPosX(), p.getPosY(),
p.getImage().getWidth(null), p.getImage().getHeight(null), null);
}
public void keyPressed(KeyEvent e) { //Method called whenever a key is pressed
if(e.getKeyChar() == new String("d").charAt(0)){
try {
moveSprite(caitlan);
} catch (InterruptedException e1) {
}
}
}
public void spawnBackground(Image backgroundImage){
Graphics g = this.getGraphics();
g.drawImage(backgroundImage, 0, 0, backgroundImage.getWidth(null),
backgroundImage.getHeight(null),null);
}
public void keyReleased(KeyEvent e) { //IGNORE
}
public void keyTyped(KeyEvent e) { //IGNORE
}
}
这里的意思是,只要按下“d”键,精灵就会向右移动 10 个像素。然而,最终发生的事情是,它被重新绘制了 10 个像素,而原始图像仍然存在,所以看起来像是一堆令人恶心的图片相互叠加。这似乎是一个相当简单的问题,但我如何简单地将精灵移动 10 像素!?