当键盘输入与字母匹配时,使字母/数字消失

时间:2013-07-19 06:35:21

标签: java keyevent

使用keyListener,当我按下我的键盘时,面板上匹配的字母/数字将消失。我的程序正在运行,但似乎我的keyListener根本不工作。需要帮助。

 import javax.swing.*;
 import java.awt.event.*;
 import java.awt.*;
 import java.util.*;

public class KeyEventSample extends JPanel{
Random r = new Random();
private String[] keyChar ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0" };
static int win_h=600;
static int win_w=800;

public KeyEventSample() {
    addKeyListener( new KeyAdapter(){             
     public void keyTyped(KeyEvent e){
        for(int q=0;q<keyChar.length;q++){
            if(String.valueOf(e.getKeyChar()).toLowerCase()==keyChar[q]){

                keyChar[q]=" ";
                repaint();
            }   
        }
     }
  });
}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    for(int z=0;z<keyChar.length;z++){
        int x=r.nextInt(win_w-100);
        int y=r.nextInt(win_h-100);
        g.setFont(new Font("Arial", Font.PLAIN, 24));
        g.drawString(keyChar[z].toUpperCase(),x,y);
    }
}   

public static void main (String[] args) {
    KeyEventSample evnt = new KeyEventSample();
    JFrame frame = new JFrame("Key Event Example");
    frame.add(evnt);
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setSize(win_w,win_h);
    frame.setVisible(true);
 }          

}

2 个答案:

答案 0 :(得分:2)

试试这个,

if(String.valueOf(e.getKeyCode()).equalsIgnoreCase(keyChar[q]))

答案 1 :(得分:0)

KeyListener中的逻辑有问题。

您实际上是在将数字与按字母顺序排列的String进行比较。

例如,'a'的键码是65.在你的KeyListener中,你真的说:65等于“a”?答案永远是否定的。

你想要做的是:

private String[] keyChar ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0" };

并将其纳入此内容:

private char[] keyChar = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0' };

然后,为条件执行此操作:

if(Character.toLowerCase(e.getKeyChar()) == keyChar[q]){