0

使用 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);
 }          

}

4

2 回答 2

2

尝试这个,

if(String.valueOf(e.getKeyCode()).equalsIgnoreCase(keyChar[q]))
于 2013-07-19T06:41:34.690 回答
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]){
于 2013-07-19T07:19:11.067 回答