java lover
java lover

Reputation: 39

why the "KeyPressed" is not work in java?

I want if I pressed 'n' char print some thing in java, I giving the action to the keylistener but I don't know why it is not worked?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JPanel implements KeyListener {


    public Test() {

           super();
           this.addKeyListener(this);
    }
 //*************key*********************************
  public void keyTyped(KeyEvent e) {
     }
  //*************key*********************************************************************
     public void keyPressed(KeyEvent e) {
         if(e.getKeyChar()=='n'){
             System.out.print("hhhhhh");

             }
    }
 //*************key**********************************************************************
     public void keyReleased(KeyEvent e) {
    }
//**************************************************

   public static void main(String[] args) {
           JFrame frame = new JFrame("java lover");
          Test panel=new Test();
          frame.add(panel);
               frame.setSize(600, 600);
               frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   }
}

thanks for helping.

Upvotes: 1

Views: 42

Answers (2)

Farzad
Farzad

Reputation: 1142

Your panel should be focusable. Change your constructor to this and it will work:

public Test() {
    super();
    setFocusable(true);
    addKeyListener(this);
}

Upvotes: 2

Peter Walser
Peter Walser

Reputation: 15706

Not all components in Swing receive key events, only those who are focussable. Add following line to your constructor, then it works:

public Test() {
    setFocusable(true);
    addKeyListener(this);
}

Code style: the explicit call to the super constuctor with super(); can be omitted (in fact, the default super constructor will get called implicitely). Also, it's not necessary to use this. when accessing local methods or fields.

Upvotes: 2

Related Questions