2011-08-05 85 views
0

我遇到了KeyListener問題。我將KeyListener添加到我創建的JPanel中,但KeyListener不起作用。KeyListener不工作?

我的主類代碼

package client; 

import java.awt.Dimension; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class KeyTest { 

    public static KeyboardEvents keyEvents; 

    public static void main(String[] args) { 
     JFrame frame = new JFrame("KeyTest"); 
     JPanel panel = new JPanel(); 

     panel.setFocusable(true); 
     panel.requestFocus(); 
     panel.addKeyListener(keyEvents); 

     frame.add(panel); 
     frame.setSize(new Dimension(640,480)); 

     frame.setVisible(true); 
    } 

} 

我對KeyboardEvents類代碼爲

package client; 

import java.awt.event.KeyEvent; 
import java.awt.event.KeyListener; 
import java.util.HashMap; 
import java.util.Map; 

public class KeyboardEvents implements KeyListener { 

    Map<Integer, Integer> keyMap; 

    public KeyboardEvents() { 
      initiate(); 
    } 

    public void initiate() { 
     keyMap = new HashMap<Integer, Integer>(); 
     } 

    public void keyPressed(KeyEvent e) { 
     keyMap.put(new Integer(e.getKeyCode()), new Integer(keyMap.size())); 
     System.out.println(e.getKeyCode()); 
    } 

    public void keyReleased(KeyEvent e) { 
     keyMap.remove(e.getKeyCode()); 
    } 

    public void keyTyped(KeyEvent e) { 
    } 

    public boolean keyDown(int key) { 
     return keyMap.containsKey(key); 
    } 

    public Integer[] getKeys() { 
     Object[] keys; 
     keys = keyMap.keySet().toArray(); 
     Integer[] c = new Integer[keys.length]; 
     for(int i = 0; i < keys.length; i++) 
     { 
      c[i] = (Integer) keys[i]; 
     } 
     return c; 
    } 

} 

我KeyboardEvents類一直爲我工作。我無法弄清楚爲什麼現在不行。

回答

2

keyEvents爲空。在你添加之前:

keyEvents= new KeyBoardEvents(); 
+0

啊,哈哈哈,我是個白癡。謝謝。 – iAndr0idOs

+0

@iAndr:是一個善良的白癡,並接受並讚揚Atreys的回答。 :) –

+0

我打算去。我不得不等待10分鐘,而我只是吃了晚飯。 ;) – iAndr0idOs