Reputation: 595
here is the scenario. I've a jtextArea in my project. On keypressed event of jtextArea I check whether pressed key is valid or not by using getKeyChar()
method of KeyEvent
. If character is valid character(according to my conditions) then it should be inserted otherwise it shouldn't be. I've searched but I couldn't find a way to cancel the event in case character is invalid. In C#
this is possible but in java
is there any way to cancel the event so that character isn't inserted in jtextarea?
here is some simple code using evt.consume()
but it's not working
private void txtArea1KeyPressed(java.awt.event.KeyEvent evt) {
evt.consume();
return;
}
Upvotes: 0
Views: 227
Reputation: 347314
Don't use KeyListener
s with text components, There is no guarantee in what order the events may be triggered, so the key may already have updated the underlying Document
by the time your listener is notified.
It also doesn't deal with what happens when the user pastes text into the field or the field is update by the program
Instead, use a DocumentFilter
, which is doesn't to allow to filter out content been pushed to the components underlying Document
model
See Implementing a Document Filter and DocumentFilter Examples
Upvotes: 2