问题
import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class AnaPencere{
JFrame pen;
AnaPencere(){
pen = new JFrame("Ana Pencere");
pen.setSize(613, 253);
pen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pen.setLocationRelativeTo(null);
pen.setResizable(false);
pen.add(new Cizim());
pen.setVisible(true);
}
private class Cizim extends JPanel{
private Cizim() {
this.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
System.out.println(e.getKeyCode());
}
});
}
}
}
When I run the project, everything works as expected, but when I press a key, I am not seeing the expected result in the console
回答1:
add
setFocusable(true)
forJPanel
with addedKeyListener
maybe there no reason to hunting for
Focus
,setFocusable
, useKeyBindings
insteadthere you can to set programatically the focus in the components hierarchy
来源:https://stackoverflow.com/questions/15599748/jpanel-keylistener-not-working