[ACCEPTED]-how to simply implement a KeyListener?-keylistener

Accepted answer
Score: 12

Here are the reasons why it doesn't work:

  1. The 11 JPanel does not have the keyboard focus. (The 10 frame has it.) You probably want to requestFocus when 9 the panel is added to the screen.

  2. You need 8 to call repaint when the graphic should change.

  3. You 7 mustn't call repaint in the paintComponent method.

  4. You need to 6 clear the drawing area before drawing the 5 string again (otherwise all characters will 4 end up on top of each other).

Here's a complete 3 working example:

class MyPanel extends JPanel implements KeyListener {
    private char c = 'e';

    public MyPanel() {
        this.setPreferredSize(new Dimension(500, 500));

    public void addNotify() {

    public void paintComponent(Graphics g) {
        g.clearRect(0, 0, getWidth(), getHeight());
        g.drawString("the key that pressed is " + c, 250, 250);

    public void keyPressed(KeyEvent e) { }
    public void keyReleased(KeyEvent e) { }
    public void keyTyped(KeyEvent e) {
        c = e.getKeyChar();

    public static void main(String[] s) {
        JFrame f = new JFrame();
        f.getContentPane().add(new MyPanel());

Oh, and you may want to 2 add f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) to make the application terminate when 1 you close the window. :-)

More Related questions