-1
public class game extends Applet implements KeyListener {
int movex = 10;
int movey = 10;
int x = 50, y = 50;
JTextArea typingArea;
Random rand = new Random();
public void paint(Graphics page){
typingArea = new JTextArea();
typingArea.addKeyListener(this);
//Drawing borders w/ Random colors
page.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
page.drawRect(0,0,200,200);
//delay
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
//Draws square
page.drawRect(x, y, 10, 10);
x+=movex;
y+=movey;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
Dimension d = getSize();
page.setColor(Color.WHITE);
page.fillRect(0, 0, d.width, d.height);
paint(page);
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println("Key is pressed");
switch(keyCode) {
case KeyEvent.VK_UP:
movex = 0;
movey = 10;
break;
case KeyEvent.VK_DOWN:
movex = 0;
movey = -10;
break;
case KeyEvent.VK_LEFT:
movex = -10;
movey = 0;
break;
case KeyEvent.VK_RIGHT :
movex = 10;
movey = 0;
break;
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent e) {
}}
目前我正在做一个快速的贪吃蛇游戏,因为我对Java相对陌生,但对编程不熟悉。使用Applet我绘制了一个正方形,并通过递增x,y坐标来移动它,然后递归地调用paint方法。我使用了错误的对象(JTextArea)还是使用了我的方法?请快速回答,谢谢。为什么这个keyListener不起作用?
“KeyListener”不起作用的“主要”原因是它从未实际注册过屏幕上显示的任何内容,因此永远无法获得键盘焦点。你不应该使用带有文本组件的'KeyListener',它完全不合适。 – MadProgrammer
我首先看看[在AWT和Swing中绘画](http://www.oracle.com/technetwork/java/painting-140037.html)和[Performing Custom Painting](http:// docs .oracle.com/javase/tutorial/uiswing/painting /)了解绘画的工作原理。然后,我将删除applet/AWT API并使用[Swing](http://docs.oracle.com/javase/tutorial/uiswing/)或JavaFX,您将获得更好的一般支持。我还会看看[如何使用Swing Timers](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html)了解如何生成游戏循环的一些想法 – MadProgrammer
你可以看看这个[例子](http://stackoverflow.com/questions/31508913/snakegame-how-to-make-the-tail-follow-the-head/31509204#31509204) 。如果你打算使用Swing,我建议看看[如何使用关键绑定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html),并忘记'KeyListener' – MadProgrammer