当我按下键盘上的"Delete"
按钮时,程序会收到三个事件 - KEY_PRESSED
,KEY_TYPED
和KEY_RELEASED
。问题是,在KEY_PRESSED
和KEY_RELEASED
中,设置了参数"keyCode"
,但在KEY_TYPED
中却没有设置(事实上,在该事件中没有有意义的信息)。使用F5
密钥,它更加有趣 - KEY_PRESSED
和KEY_RELEASED
已注册,但KEY_TYPED
永远不会发生。
通过Toolkit.getDefaultToolkit().addAWTEventListener()
添加了侦听器。使用JDK 6.26。
可能是我的问题?
编辑:
以下是按下Delete
键时发生的事件:
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=127,keyText=Delete,keyChar=Delete,keyLocation=KEY_LOCATION_STANDARD,rawCode=119,primaryLevelUnicode=127,scancode=0] on javax.swing.JButton[,0,0,61x30,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.synth.SynthBorder@50f38cf0,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon@6ae2d0b2,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=SVG,defaultCapable=false]
java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar=Delete,keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=127,scancode=0] on javax.swing.JButton[,0,0,61x30,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.synth.SynthBorder@50f38cf0,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon@6ae2d0b2,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=SVG,defaultCapable=false]
java.awt.event.KeyEvent[KEY_RELEASED,keyCode=127,keyText=Delete,keyChar=Delete,keyLocation=KEY_LOCATION_STANDARD,rawCode=119,primaryLevelUnicode=127,scancode=0] on javax.swing.JButton[,0,0,61x30,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.synth.SynthBorder@50f38cf0,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon@6ae2d0b2,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=SVG,defaultCapable=false]
答案 0 :(得分:5)
更好的是实施KeyBindings
键盘的一部分是保留内置JComponent功能的键,来自@camickrs的更多信息UIManager Defaults
取决于你需要实现KeyListener的原因,因为对于各种JComponent有很多其他的监听器,它应该在内部过滤或注册文本更改
一些JComponent模型从鼠标和键盘输入生成事件
答案 1 :(得分:1)
来自JavaDoc The "key typed" event. This event is generated when a character is entered. In the simplest case, it is produced by a single key press. Often, however, characters are produced by series of key presses, and the mapping from key pressed events to key typed events may be many-to-one or many-to-many.
您正在尝试获取可能未注册为输入字符的F5键。通过使用KEY_RELEASED,您将始终获得您正在寻找的结果,并且API的行为符合预期。
答案 2 :(得分:1)
键入事件总是生成'0'作为键码。相反,查找方法getKeyChar(),或者(如已建议的那样)侦听keyReleased()。 getKeyChar():http://goo.gl/ajH03