KeyListener not working?

2019-09-09 15:27发布

问题:

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

}

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.

回答1:

keyEvents is null. before you add it:

keyEvents= new KeyBoardEvents();