Rajakumar Rajakumar - 9 days ago 5
Java Question

KeyListener doesnot works

KeyListener Does not works.
I have two class the main class and the pannel and i linked the panel using the setContentPane() function. i have implemented the keylistener in the Panll.java it seems the keylistener is not working.
SamG.java

package samg;

import javax.swing.JFrame;

/**
*
* @author mca-hp-188
*/
public class SamG{


public static void main(String[] args) {
JFrame jf = new JFrame("My APP");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(800, 400);
jf.setVisible(true);
jf.pack();
jf.setContentPane(new Panll());
}
}

package samg;

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
*
* @author mca-hp-188
*/
public class Panll extends JPanel implements KeyListener{
int x=100,y=100;
boolean run=true;
Panll(){
addKeyListener(this);
}
@Override
public void paint(Graphics g){
super.repaint();
g.clearRect(0, 0, 800, 400);
update();
draw(g);
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
Logger.getLogger(Panll.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void update(){
x++;
y++;
}
public void draw(Graphics g){
g.drawOval(x, y, 100, 100);
}

@Override
public void keyTyped(KeyEvent e) {

}

@Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar());
}

@Override
public void keyReleased(KeyEvent e) {

}
}

Answer

you can't focus a JPanel without explicit allowing it with setFocusable(true);. if you add this line you can take you focus on the JPanel. if you then press any button the KeyListener works just fine

Comments