1

给定以下(部分)代码:

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

4

1 回答 1

1
  1. 更改(key == 'F')if (key.equals('F')). 测试对象等价而不是等价。
  2. 确保组件是focusable& to requestFocusInWindow()。后者最好通过@Overrideonstart()方法来完成。
  3. 考虑使用 Swing( JApplet) 和键绑定而不是 AWTAppletKeyListener.
于 2013-03-26T13:35:26.720 回答