简体   繁体   中英

Java String comparison fails within KeyListener

I am having an incredibly frustrating time trying to figure out why a KeyListener wont fully execute. It must be something in Java of which I am just unaware.

I'm trying to use a KeyListener to catch the user entering text into a JTextArea via the "Enter" Key. When the user presses Enter, the String they entered into the JTextArea is saved via .getText(); and is then compared to another String to see if they match using .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.

Below is the example of my code. In this example, I'm trying to get the program to execute System.exit(0); in the event the user types the word "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. Perhaps there is extra whitespace in the JTextArea .

Try test.trim().equalsIgnoreCase(quit)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM