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