我为我之前的问题找到了解决方案,这让我陷入了新的问题。
在以下代码中,我使用箭头键在 JFrame 周围移动图像。但是每次我按下箭头键时,图像似乎都会闪烁,当连续按下一个键时,这一点非常明显。
import java.awt.Graphics;
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;
public class TestProgram extends JFrame implements KeyListener {
private BufferedImage TestImage;
private int cordX = 100;
private int cordY = 100;
public TestProgram() {
setTitle("Testing....");
setSize(500, 500);
imageLoader();
setVisible(true);
}
public void imageLoader() {
try {
String testPath = "test.png";
TestImage = ImageIO.read(getClass().getResourceAsStream(testPath));
} catch (IOException ex) {
ex.printStackTrace();
}
addKeyListener(this);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(TestImage, cordX, cordY, this);
}
public static void main(String[] args) {
new TestProgram();
}
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) {}
}
有什么办法可以避免这种情况吗?
编辑:以上是完整的工作代码。我发现很难在其中加入双缓冲。任何人都可以在这方面帮助我吗?