Java KeyListener: KeyTyped Backspace, Esc as input

前端 未结 7 1012
耶瑟儿~
耶瑟儿~ 2020-12-29 10:33

Inside the KeyTyped method, how do I tell if Backspace or Esc is being pressed?

相关标签:
7条回答
  • 2020-12-29 10:55

    http://www.fileformat.info/info/unicode/char/8/index.htm

    When arg0.getKeyChar() is cast to an int: (int)arg0.getKeyChar(), The backspace key comes up with the value 8, and the Esc key comes up with the value 27.

    0 讨论(0)
  • 2020-12-29 11:01

    I understand this is a very old subject, but I wanted to add an answer that I found helped me greatly with the same issue.

    I'm making a chat input for a Java program, and its better to use KeyTyped as opposed to pressed and released (as it excluded the need to filter most characters). Anyways I wanted to make backspace delete characters, but the .getKeyCode() always returned 0 as per the documentation. However, you can use .getKeyChar() to return the character (probably will appear as a square box), and the escape character '\b' to do a comparison.

    if(tmp.getKeyChar().equals('\b')) { ... }
    
    0 讨论(0)
  • 2020-12-29 11:01

    You can also use e.getExtendedKeyCode() in keyTyped and it returns non-zero values that appear correct.

    0 讨论(0)
  • 2020-12-29 11:02

    Assuming you have attached the KeyListener properly and have implemented the methods required for that KeyListener, to detect specific key-presses simply add the following code:

    public void keyReleased(KeyEvent ke) 
    {
        if(ke.getKeyCode() == KeyEvent.VK_BACK_SPACE)
        {  
            //code to execute if backspace is pressed
        }
    
        if(ke.getKeyCode() == KeyEvent.VK_ESCAPE)
        {
            //code to execute if escape is pressed
        }
    }
    

    The KeyEvent class javadocs can be found at the following link: KeyEvent javadocs.
    There you can find a list of all of the Java virtual keycodes used to detect keyboard input when implementing Java KeyListeners and KeyEvents. More information about KeyListeners can be found here: How to Write a Key Listener. To use the keyTyped method as asked, see gangqinlaohu's answer.

    0 讨论(0)
  • 2020-12-29 11:02

    Only for java 7 / jdk1.7 and above: In case you are checking against event.getKeyCode(), try the event.getExtendedKeyCode() method. In case of the back-space it will return the proper code (in this case, 8) instead of a plain 0. That way there is no need to check against \b:

    if (e.getExtendedKeyCode() == KeyEvent.VK_BACK_SPACE) {
        System.out.println("Backspace pressed");
    }
    
    0 讨论(0)
  • 2020-12-29 11:04

    Check below code, I hope it will work for you.

    @FXML
    public void keyPresses(KeyEvent ke) 
    {
        if (ke.getCode().equals(KeyCode.BACK_SPACE)) {
            System.out.println("It Works Backspace pressed..!");
        }
    }
    
    0 讨论(0)
提交回复
热议问题