这是我的问题。当我尝试处理 KB 事件时,我的程序什么也不做。有些人认为它发生是因为忙于等待(新线程与主线程发生冲突)。我该如何解决?
public class GameCanvas extends Canvas {
int myX = 250;
int myY = 0;
int speedValue = 15;
int bottom = 480;
GameCanvas() {
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.VK_LEFT:
if (myX > 5) myX -= 5;
break;
case KeyEvent.VK_RIGHT:
if (myX < 480) myX += 5;
break;
}
repaint();
}
});
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
setGameSpeed(speedValue);
if (myY < bottom) {
myY += 5;
} else {
bottom -= 20;
myY = 0;
}
repaint();
}
}
}).start();
}
public void setGameSpeed(int value) {
try {
sleep(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void paint(Graphics g) {
g.setColor(Color.darkGray);
g.fillRect(myX, myY - 5, 25, 25);
buildGameBottom(g);
}
void buildGameBottom(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, bottom + 20, 500, bottom + 20);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame();
GameCanvas gameCanvas = new GameCanvas();
gameCanvas.setSize(new Dimension(500, 500));
gameCanvas.setBackground(Color.LIGHT_GRAY);
gameCanvas.requestFocus();
frame.add(gameCanvas);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}