我正在尝试用Java制作一个正方形的动画,但是当我按下按键时,正方形背后会留下一条痕迹。我想让广场本身移动而不留下像蛇一样的痕迹。
我该如何解决这个问题?我能做些什么来解决它吗?
这是我的代码:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Main extends Canvas implements KeyListener, Runnable {
Thread t;
boolean running = false;
int x = 200;
int y = 200;
int velx;
int vely;
public Main() {
setFocusable(true);
requestFocus();
addKeyListener(this);
}
public void run() {
while (running) {
render();
tick();
}
stop();
}
synchronized void start() {
if (running) return;
running = true;
t = new Thread(this);
t.start();
}
synchronized void stop() {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(1);
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.CYAN);
g.fillRect(x, y, 300, 300);
g.dispose();
bs.show();
}
public void tick() {
x += velx;
y += vely;
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_RIGHT) {
velx += 5;
} else if (key == KeyEvent.VK_LEFT) {
velx -= 5;
} else if (key == KeyEvent.VK_DOWN) {
vely += 5;
} else if (key == KeyEvent.VK_UP) {
vely -= 5;
}
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
velx = 0;
vely = 0;
}
public static void main (String args[]){
JFrame frame = new JFrame("Animation");
Main main = new Main();
frame.setSize(1200, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(main);
frame.setResizable(false);
frame.setVisible(true);
main.start();
}
}
答案 0 :(得分:0)
在绘制带有更新坐标的新方块之前,您应该始终擦除已在画布上绘制的方块(即用背景颜色覆盖它)。为此,您可以按如下方式修改代码:
int prevX, prevY;
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
// erase the previous square
g.setColor(getBackground());
g.fillRect(prevX, prevY, 300, 300);
// draw the new square
g.setColor(Color.CYAN);
g.fillRect(x, y, 300, 300);
g.dispose();
bs.show();
}
public void tick() {
// backup the previous coordinates
prevX = x;
prevY = y;
x += velx;
y += vely;
}