KeyListener仅检测一次退格 [英] KeyListener detecting backspace only once
问题描述
我正在创建一个自定义文本字段(绘制文本而不是使用JTextField).我可以输入字符,但是退格键只能清除一个字符.然后,如果我再写一些东西,我可以再次删除一个字符.我不知道为什么.
I'm making a custom textfield (drawing the text instead of using JTextField). I can type the characters in, but the backspace only clears one character. Then if I write something more, I can delete one character again. I have no idea why.
KeyListener:
KeyListener:
class KeyController implements KeyListener {
public void keyPressed(KeyEvent e) {
if (!chat.getUsing()) {
player.keyPressed(e);
} else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
chat.keyTyped(e);
}
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (chat.getUsing()) {
chat.setUsing(false);
} else {
chat.setUsing(true);
}
}
}
public void keyReleased(KeyEvent e) {
if (!chat.getUsing()) {
player.keyReleased(e);
}
}
public void keyTyped(KeyEvent e) {
if (chat.getUsing() && e.getKeyCode() != KeyEvent.VK_BACK_SPACE) {
chat.keyTyped(e);
}
}
}
聊天对象中的keyTyped()方法:
The keyTyped() method in the chat object:
public void keyTyped(KeyEvent ev) {
if (ev.getKeyCode() != KeyEvent.VK_BACK_SPACE) {
currentText += ev.getKeyChar();
} else {
if (currentText.length() > 0) {
currentText = currentText.substring(0, currentText.length() - 1);
}
}
}
我正在绘制currentText字符串.
And I'm drawing out the currentText string.
推荐答案
尝试这个
e.getKeyChar() != KeyEvent.VK_BACK_SPACE
代替
e.getKeyCode() != KeyEvent.VK_BACK_SPACE
在keyTyped()
方法中.
直接来自KeyEvent
getKeyChar方法始终返回有效的Unicode字符或CHAR_UNDEFINED.字符输入由KEY_TYPED事件报告:KEY_PRESSED和KEY_RELEASED事件不一定与字符输入关联.因此,保证getKeyChar方法的结果仅对KEY_TYPED事件有意义.
The getKeyChar method always returns a valid Unicode character or CHAR_UNDEFINED. Character input is reported by KEY_TYPED events: KEY_PRESSED and KEY_RELEASED events are not necessarily associated with character input. Therefore, the result of the getKeyChar method is guaranteed to be meaningful only for KEY_TYPED events.
对于按下键和释放键的事件,getKeyCode方法返回事件的keyCode.对于键类型的事件,getKeyCode方法始终返回VK_UNDEFINED . getExtendedKeyCode方法也可以与许多国际键盘布局一起使用.
For key pressed and key released events, the getKeyCode method returns the event's keyCode. For key typed events, the getKeyCode method always returns VK_UNDEFINED. The getExtendedKeyCode method may also be used with many international keyboard layouts.
有关更多信息,请在此处阅读有关关键事件的信息.
For more info read here about Key Event.
这篇关于KeyListener仅检测一次退格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!