[英]Java String comparison fails within KeyListener
I am having an incredibly frustrating time trying to figure out why a KeyListener wont fully execute. 我有一个令人难以置信的令人沮丧的时间试图弄清楚为什么KeyListener不会完全执行。 It must be something in Java of which I am just unaware. 它必须是Java中我不知道的东西。
I'm trying to use a KeyListener to catch the user entering text into a JTextArea via the "Enter" Key. 我正在尝试使用KeyListener来捕获用户通过“Enter”键将文本输入JTextArea。 When the user presses Enter, the String they entered into the JTextArea is saved via .getText();
当用户按Enter键时,他们输入JTextArea的String通过.getText();
保存.getText();
and is then compared to another String to see if they match using .equalsIgnoreCase();
然后将其与另一个String进行比较,以查看它们是否匹配使用.equalsIgnoreCase();
, but the program seems to completely ignore this batch of code. ,但该程序似乎完全忽略了这批代码。 I've been trying to find my error on and off for 3 days now and can't think of anything. 我一直试图找到我的错误3天,现在不能想到任何事情。
Below is the example of my code. 以下是我的代码示例。 In this example, I'm trying to get the program to execute System.exit(0);
在这个例子中,我试图让程序执行System.exit(0);
in the event the user types the word "quit". 如果用户键入单词“quit”。 Any help is appreciated. 任何帮助表示赞赏。 I'm really hoping I didn't just forget something stupid. 我真的希望我不会忘记一些愚蠢的事情。
playerInput.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER) {
String test = playerInput.getText();
String quit = "quit";
playerInput.setText("");
if(test.equalsIgnoreCase(quit))
System.exit(0);
}
}
public void keyPressed(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
This should work: 这应该工作:
playerInput.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER) {
String test = playerInput.getText().replaceAll("\\r|\\n", "");
String quit = "quit";
playerInput.setText("");
if(test.equalsIgnoreCase(quit))
System.exit(0);
}
}
public void keyPressed(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
为什么不使用DocumentListener并在文档持有的文本包含单词“quit”时签入。
Is the user typing "quit" or "quit\\n\\r" ... if you get my drift. 用户输入“退出”或“退出\\ n \\ r”......如果你得到我的漂移。 Perhaps there is extra whitespace in the JTextArea
. 也许JTextArea
有额外的空格。
Try test.trim().equalsIgnoreCase(quit)
试试test.trim().equalsIgnoreCase(quit)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.