我有代码:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class obj_Dingus
extends Applet
implements KeyListener{
private Rectangle rect; //The rectangle that we move
public void init()
{
this.addKeyListener(this);
rect = new Rectangle(0, 0, 50, 50);
}
public void paint(Graphics g)
{
setSize(500,500);
Graphics2D g2 = (Graphics2D)g;
g2.fill(rect);
}
@Override
public void keyPressed(KeyEvent e) {
repaint();
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
rect.setLocation(rect.x + 2, rect.y);
} if (e.getKeyCode() == KeyEvent.VK_LEFT){
rect.setLocation(rect.x - 2, rect.y);
} if (e.getKeyCode() == KeyEvent.VK_UP){
rect.setLocation(rect.x, rect.y - 2);
} if (e.getKeyCode() == KeyEvent.VK_DOWN){
rect.setLocation(rect.x, rect.y + 2);
}
repaint();
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
据我所知,它应该制作一个在屏幕周围移动的黑框,但屏幕没有更新,旧框也没有清除。它最终在屏幕上出现一条巨大的黑线,我不知道我做错了什么,我是一个完全的初学者。