Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

java - How to detect backspace in a keyTypedEvent

I'm using Netbeans' bean form to create my GUI.
I've added a keyTyped event to a JTextArea and I want to detect if the typed key is a Backspace.

I'm using keyTyped event for other reasons so I cannot just use the keyPressed event.

This is the generated code (and my if check):

private void langArea1KeyTyped(java.awt.event.KeyEvent evt) {   

    if(evt.getChar()== backspace) //how can I make this check?   
}     

evt.getKeyCode() always returns 0 independent of the typed key.
evt.getKeyChar() simply deletes the last character printed when printed so I can't use System.out.print(evt.getKeyChar()) to detect its value and check for it.

How can I detect if the typed key is Backspace (or Delete)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot use keyTyped, you need to use either keyPressed or keyReleased to determine if backspace character has been typed. The keyTyped event only picks up non-escape characters (only characters that can be displayed).

The backspace character can be checked with KeyEvent.VK_BACK_SPACE.

Try adding this listener to the keyPressed event:

import java.awt.event.KeyEvent;

private void langArea1KeyPressed(KeyEvent evt) {   
    if (evt.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
        // Do something...
    }
}

Additional Reading

You can check out the official Java tutorial on How to Write a Key Listener.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...