KeyListener不会产生任何响应

时间:2013-03-26 09:33:39

标签: java awt listener keylistener

给出以下(部分)代码:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Test extends Applet implements MouseListener , KeyListener
{
    private static final long serialVersionUID = 1L;
    private static final int TOTAL_POINTS = 500;
    private static final int THRESHOLD = 5;

    // the arrays that contain the indexes of the points that the user created 
    private int[] m_Xindex, m_yIndex;  

    // The number of points that the user created 
    private int m_pointsCreated;       

    @Override
    public void keyTyped(KeyEvent keyEvent) 
    {
          char key = keyEvent.getKeyChar();
          if (key == 'F')
              System.out.println("123");
    } 

    @Override
    public void mouseReleased(MouseEvent arg0) {/* Empty */ }

    @Override
    public void mouseClicked(MouseEvent e) {/* Empty */ }

    @Override
    public void mouseEntered(MouseEvent e) {/* Empty */ }

    @Override
    public void mouseExited(MouseEvent e) {/* Empty */ }

    @Override
    public void mousePressed(MouseEvent myEvent) {/* Empty */ }

    @Override
    public void keyPressed(KeyEvent keyEvent)  {}

    @Override
    public void keyReleased(KeyEvent keyEvent) {}
}  

我删除了我的工作代码,只留下了有问题的代码。

当我按F时,我想打印到屏幕123,但没有 打印到屏幕上。

keyTyped的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

  1. (key == 'F')更改为if (key.equals('F'))。测试对象等价而不是相等。
  2. 确保该组件为focusable&到requestFocusInWindow()。后者最好由@Override方法上的start()完成。
  3. 考虑使用Swing(JApplet)和键绑定而不是AWT AppletKeyListener