开发者

KeyListener not working?

I'm having trouble with a KeyListener. I add the KeyListener to the JPanel that I create, but the KeyListener isn't working.

My code for the main class is

package client;

import java.awt.Dimension;

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

public class KeyTest {

    public static KeyboardEvents keyE开发者_StackOverflow中文版vents;

    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);
    }

}

My code for the KeyboardEvents class is

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;
    }

}

My KeyboardEvents class has always worked for me. I can't figure out why it won't work now.


keyEvents is null. before you add it:

keyEvents= new KeyBoardEvents();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜