如何简单地实现KeyListener?

时间:2012-02-17 19:02:40

标签: java swing keylistener

public class MyPanel extends JPanel implements KeyListener {
    private char c = 'e';
    public MyPanel() {
        this.setPreferredSize(new Dimension(500,500));
        addKeyListener(this);
    }
    public void paintComponent(Graphics g) {
        super.repaint();
        g.drawString("the key that pressed is" + c, 250,250);
    }

    public void keyPressed(KeyEvent e) {
        c=e.getKeyChar();
        repaint();

    }

    public void keyReleased(KeyEvent e) {
    }


    public void keyTyped(KeyEvent e) {
        c=e.getKeyChar();
        repaint();
    }

    public static void main(String[] s) {
        JFrame f=new JFrame();
        f.getContentPane().add(new MyPanel());
        f.pack();
        f.setVisible(true);
    }
}

我尝试阅读this但却无法理解如何简单地实现KeyListener。那么我需要改变什么呢?

1 个答案:

答案 0 :(得分:11)

以下是它不起作用的原因:

  1. JPanel没有键盘焦点。 (框架有它。)当面板添加到屏幕时,您可能希望requestFocus

  2. 当图片发生变化时,您需要致电repaint

  3. 您不得在repaint方法中致电paintComponent

  4. 您需要在再次绘制字符串之前清除绘图区域(否则所有字符将最终在彼此之上)。

  5. 这是一个完整的工作示例:

    class MyPanel extends JPanel implements KeyListener {
        private char c = 'e';
    
        public MyPanel() {
            this.setPreferredSize(new Dimension(500, 500));
            addKeyListener(this);
        }
    
        public void addNotify() {
            super.addNotify();
            requestFocus();
        }
    
        public void paintComponent(Graphics g) {
            g.clearRect(0, 0, getWidth(), getHeight());
            g.drawString("the key that pressed is " + c, 250, 250);
        }
    
        public void keyPressed(KeyEvent e) { }
        public void keyReleased(KeyEvent e) { }
        public void keyTyped(KeyEvent e) {
            c = e.getKeyChar();
            repaint();
        }
    
        public static void main(String[] s) {
            JFrame f = new JFrame();
            f.getContentPane().add(new MyPanel());
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setVisible(true);
        }
    }
    

    哦,你可能想要在关闭窗口时添加f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)以使应用程序终止。 : - )