I have a JTextArea which is uneditable under a certain setting. However, under this setting the user can still use the space and backspace keys. To accommodate the space, I have the following code,
if (e.getKeyChar() == KeyEvent.VK_SPACE) {
editor.insert(" ", editor.getCaretPosition());
}
I’m having an issue with backspace though. I’ve tried this,
if (e.getKeyChar() == KeyEvent.VK_BACK_SPACE) {
editor.insert("\b", editor.getCaretPosition());
}
That seems to add a tiny space when backspace is pressed. It’s not as much as a space, and it’s almost unnoticeable when pressed once. It’s definitely not a backspace though. Worse case I’ll have to copy all the characters up to the caret position – 1 and append them to all the characters after the caret position, but I don’t like that solution.
Use Key Bindings to allow the space and backspace keys to have associated actions, and then remove a character from the JTextArea’s Document if backspace has been pressed.
For example,