anonymous
anonymous

Reputation: 498

JPanel not responding to keylistener

I tried to make a JPanel that would display how many times you press each navigation key, but it is only displaying 4 zeros.

//In the keyPressed() method, I put the following code that handles key presses accordingly:

public void keyPressed(KeyEvent event) 
{
    if(event.getKeyCode()==KeyEvent.VK_LEFT)
    left++;             
    else if(event.getKeyCode()==KeyEvent.VK_RIGHT)
    right++;            
    else if(event.getKeyCode()==KeyEvent.VK_UP)
    up++;               
    else if(event.getKeyCode()==KeyEvent.VK_DOWN)
    down++;
}

//the paint method to paint the counts over JPanel

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    g.drawString ( Integer.toString(left),   100, 100 );
    g.drawString ( Integer.toString(right),  200, 100 );
    g.drawString ( Integer.toString(up),     100, 200 );
    g.drawString ( Integer.toString(down),   200, 200 );    
}

Upvotes: 1

Views: 132

Answers (2)

Braj
Braj

Reputation: 46841

  • Call repaint(); in keyPressed() method in the end.

  • Call count_keys.setFocusable(true); in main method just below its creation

Because JPanel is not focus able hence KeyListener is not working.

Upvotes: 6

MadProgrammer
MadProgrammer

Reputation: 347194

Welcome to the wonderful world of KeyListeners.

KeyListeners by design, can only respond to key events when the component they are registered to is focusable AND has focus.

This generally makes them a poor choice in a gaming environment, where you might have a number of components that can steal focus from you main game component.

Instead, you should be using Key bindings

Upvotes: 5

Related Questions