2012-04-15 31 views
1

我已經開始在java中編寫一個簡單的平臺遊戲。作爲測試,我編寫了這個簡單的 程序,當您按下箭頭鍵時,該程序會圍繞該小程序移動一個矩形。關鍵事件一直沒有解除。這裏是代碼:Java - KeyListener事件沒有觸發

import java.applet.*; 
import java.awt.*; 
import java.awt.event.*; 
public class Game extends Applet implements Runnable, KeyListener 
{ 
    //setup data 
    Thread t; 
    Image buffimg; 
    Graphics draw; 
    Dimension dim; 

    //game variables 
    int charx = 400;//rectangles X and Y positions 
    int chary = 50; 
    boolean leftArrow = false; 
    public void init() 
    { 
     setSize(800, 500); 
     t = new Thread(this); 
     t.start(); 
     addKeyListener(this); 
    } 
    public void run() 
    { 
     while(true) 
     { 
      repaint(); 
      moveChar();//move the rectangle 
      try { 
       t.sleep(1000/30); 
      } catch (InterruptedException e) { ; } 
     } 
    } 
    public void keyPressed(KeyEvent e) 
    { 
     int k = e.getKeyCode(); 
     if(k == 37) 
     { 
      leftArrow = true; 
      charx--; 
     } 

    } 
    public void keyReleased(KeyEvent e) 
    { 
     if(e.getKeyCode() == 37) 
     { 
      leftArrow = false; 
     } 
    } 
    public void keyTyped(KeyEvent e) 
    { 
    } 
    public void moveChar() 
    { 
     //move rectangle on left arrow key press 
     if(leftArrow == true) 
     { 
      charx--; 
     } 
    } 
    public void paint(Graphics g) 
    { 
     g.drawRect(charx, chary, 100, 100); 
    } 
    public void update (Graphics g) 
    { 
     //double buffering 

     // initialize buffer 
     if (buffimg == null) 
     { 
      buffimg = createImage (this.getSize().width, this.getSize().height); 
      draw = buffimg.getGraphics(); 
     } 
     // clear screen in background 
     draw.setColor (getBackground()); 
     draw.fillRect (0, 0, this.getSize().width, this.getSize().height); 
     // draw elements in background 
     draw.setColor (getForeground()); 
     paint (draw); 
     // draw image on the screen 
     g.drawImage (buffimg, 0, 0, this); 
    } 
} 

他們爲什麼不開火,我該如何解決這個問題?

+0

我能矩形向左移動withouth的問題。你確定你運行了最新版本的代碼嗎? – Rob 2012-04-15 19:20:45

+0

是的,這可能是我的月食設置的問題嗎? – Joe 2012-04-15 19:23:39

+0

感謝安德魯,這似乎已修復它。 – Joe 2012-04-15 19:31:00

回答

4
this.requestFocusInWindow(); // end of init(), or better, in start() 
+0

+1 hmmm repaint();然後moveChar(); ? – mKorbel 2012-04-15 19:44:40

1

我試過了你的代碼。它的工作原理應該如此。

問題在於,您需要在繪圖區域上按下鼠標才能將其聚焦,然後才能接收事件。

來自動執行,使用這個命令:requestFocusInWindow()

+0

對不起,在我測試你的代碼的時候,Andrew發佈了答案。 – 2012-04-15 19:46:54

+0

+1「*我正在測試你的代碼」*我沒有打擾,我的只是一個受過教育的猜測。 ;) – 2012-04-15 20:04:38

+0

很酷,謝謝。我也提高了你的帖子。 :) – 2012-04-15 20:16:19