Rajakumar Rajakumar - 14 days ago 8
Java Question

KeyListener doesn't work

I have the following two classes, the main-class (SamG) and the Panll-class. I have implemented the KeyListener in the Panll-class, but it doesn't seem to work.

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

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