Zohaib Aslam
Zohaib Aslam

Reputation: 595

how to cancel jtextarea event?

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

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347314

Don't use KeyListeners 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

Pieter De Bie
Pieter De Bie

Reputation: 1212

End your event handler with

event.consume()

event.consume() docs

Upvotes: 1

Related Questions