的JPanel的KeyListener不工作(JPanel KeyListener Not Work

2019-10-17 21: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());
                }
            });
        }
    }
}

当我运行该项目,一切正常,但是当我按一个键,我没有看到在控制台中预期的结果

Answer 1:

  • 添加setFocusable(true)JPanel添加了KeyListener

  • 也许有没有理由去打猎FocussetFocusable ,使用KeyBindings ,而不是

  • 那里,你可以到设置在编程的组件层次结构中的焦点



文章来源: JPanel KeyListener Not Working