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());
}
});
}
}
}
当我运行项目时,一切都按预期工作,但是当我按下一个键时,我没有在控制台中看到预期的结果
答案 0 :(得分:7)
为setFocusable(true)
添加JPanel
并添加KeyListener
也许没有理由寻找Focus
,setFocusable
,而是使用KeyBindings
您可以set programatically the focus in the components hierarchy