我正在学习如何用键盘监听器对键盘输入进行编码。我通过以下程序使用它:
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class KeyboardInput extends JFrame implements KeyListener {
public KeyboardInput(String s) {
super(s);
JPanel panel = new JPanel();
JLabel label = new JLabel();
panel.add(label);
add(panel);
addKeyListener(this);
setSize(200, 100);
setVisible(true);
}
public void keyTyped(KeyEvent event) {
KeyEvent e = event;
switch(e.getKeyCode()) {
case java.awt.event.KeyEvent.VK_A: System.out.println("A");
case java.awt.event.KeyEvent.VK_D: System.out.println("D");
case java.awt.event.KeyEvent.VK_S: System.out.println("S");
case java.awt.event.KeyEvent.VK_W: System.out.println("W");
case java.awt.event.KeyEvent.VK_SPACE: System.out.println("Space");
}
if (e.getKeyCode() == java.awt.event.KeyEvent.VK_0) {
System.out.println("0");
}
}
public void keyPressed(KeyEvent event) {
if(event.getKeyCode() == java.awt.event.KeyEvent.VK_W) {
System.out.println("W");
}
}
public void keyReleased(KeyEvent e) {
// nothing yet
}
}
public class Core {
public static boolean isRunning = true;
public static void main(String args[]) {
new KeyboardInput("Keyboard Input Testing");
}
}
不幸的是,有一个大问题:当keyPressed事件正在工作时,keyTyped事件却没有。这是我的代码中的错误,还是可能是由于键盘故障引起的?
我还有一个额外的澄清问题是:为什么在主类中初始化了KeyboardInput而未声明它被初始化了?
答案 0 :(得分:0)