JPanel KeyListener Not Working

笑着哭i 提交于 2020-01-05 10:26:17

问题


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) for JPanel with added KeyListener

  • maybe there no reason to hunting for Focus, setFocusable, use KeyBindings instead

  • there you can to set programatically the focus in the components hierarchy



来源:https://stackoverflow.com/questions/15599748/jpanel-keylistener-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!