-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