所以我正在制作这个 java 小程序,我只想先确保键输入正常工作,然后再让它变得更复杂。我不知道为什么,但是当你删除“System.out.print(needUpdating);” 它没有根据键输入正确移动矩形。谁能告诉我为什么以及如何解决它?这对我来说完全是个谜。
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JApplet;
public class firstApplet extends JApplet implements KeyListener, Runnable {
final int MOVEAMOUNT = 1;
boolean needUpdating;
int x,y,dx,dy;
Thread runner = null;
public void init() {
this.setFocusable(true);
needUpdating = false;
this.requestFocusInWindow();
x=0;
y=0;
dx=0;
dy=0;
addKeyListener(this);
}
public void stop() {
}
public void start() {
runner = new Thread(this);
runner.start();
}
public void paint(Graphics g) {
System.out.println("x= "+x+" y = "+y);
g.drawRect( x, y, 100, 15 );
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key==KeyEvent.VK_UP) {
System.out.println("up");
dy=MOVEAMOUNT;
}
else if (key==KeyEvent.VK_DOWN) {
dy=-MOVEAMOUNT;
}
else if (key==KeyEvent.VK_LEFT) {
dx=-MOVEAMOUNT;
}
else if (key==KeyEvent.VK_RIGHT) {
dx=MOVEAMOUNT;
}
// TODO Auto-generated method stub
needUpdating = true;
System.out.println("needUpdating listening = " +needUpdating);
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
dx=0;
dy=0;
}
@Override
public void keyTyped(KeyEvent e) {
}
public void processMovement() {
System.out.println("processing");
x+=dx;
y+=dy;
}
@Override
public void run() {
this.addKeyListener(this);
while(true) {
System.out.print(needUpdating);
if(needUpdating) {
processMovement();
repaint();
needUpdating=false;
}
}
}
}