Java 将键输入附加到字符串
Java Append Key Input to String
对于我当前的项目,我需要创建一个自定义文本框来按下每个键并将其添加到一个字符串中。我不断更新检索用户按下的键的方法,然后像这样添加它:
public void addCharacter(String c) {
String before = text;
String after = before;
if (!before.endsWith(c)) {
after = text + c;
} else {
//What can I do here to check if the key
//was released and then pressed again, so that
//it only adds the character the number of times the user presses the key.
}
text = after;
}
我的问题是,如果我键入一个键,它会添加大量的键,因为它会不断更新,这就是为什么我必须检查它是否与以前相同的字母,而不是添加它。
编辑:
我们如何添加密钥的示例:
if (key.a) {
addCharacter("a");
return;
}
我认为您可以使用 KeyListener
来完成这项工作。这基本上是一个侦听器,每次键入、按下和释放键时都会发送事件。简而言之,我会收听 keyPressed
事件,然后在收到 keyReleased
事件之前不会输入该字母。
对于我当前的项目,我需要创建一个自定义文本框来按下每个键并将其添加到一个字符串中。我不断更新检索用户按下的键的方法,然后像这样添加它:
public void addCharacter(String c) {
String before = text;
String after = before;
if (!before.endsWith(c)) {
after = text + c;
} else {
//What can I do here to check if the key
//was released and then pressed again, so that
//it only adds the character the number of times the user presses the key.
}
text = after;
}
我的问题是,如果我键入一个键,它会添加大量的键,因为它会不断更新,这就是为什么我必须检查它是否与以前相同的字母,而不是添加它。
编辑: 我们如何添加密钥的示例:
if (key.a) {
addCharacter("a");
return;
}
我认为您可以使用 KeyListener
来完成这项工作。这基本上是一个侦听器,每次键入、按下和释放键时都会发送事件。简而言之,我会收听 keyPressed
事件,然后在收到 keyReleased
事件之前不会输入该字母。