Cut and Paste in JTextArea

I am developing an application that requires only 165 characters in JTextArea. I imposed this condition. I used a static counter to count the number of characters entered in the text box, and also encoded to handle the condition that when the user removes any line from the text, the counter should be increased, given the length of the selected line.

However, now I want to handle the condition when the user performs the function "cut" or "paste" by pressing "Ctrl + X" and "Ctrl + V". I know that the default methods from JTextComponent are inherited in JTextArea, but I want to get the cut text and find out the length of the cut text to reduce the counter supported for characters and increase it when pasted by the corresponding amount.

+4
source share
3 answers

It looks like you need to use DocumentListener to track changes. Events in the document listener will tell you how many characters are added / removed in any given change, and also gives a link to the Document , which supports the text area.

The following is an example implementation of a document listener for a JTextArea called textArea :

 textArea.getDocument().addDocumentListener( new DocumentListener() { public void changedUpdate( DocumentEvent e ) { } public void insertUpdate( DocumentEvent e ) { System.out.println( "insertUpdate: Added " + e.getLength() + " characters, document length = " + e.getDocument().getLength() ); } public void removeUpdate( DocumentEvent e ) { System.out.println( "removeUpdate: Removed " + e.getLength() + " characters, document length = " + e.getDocument().getLength() ); } }); 

This listener will detect cutouts and pastes, as well as keystrokes.

+3
source

Create a DocumentFilter and set it to the new PlainDocument . Use this document to create a JTextArea . (Or use the default document for JTextArea, after it has been passed to AbstractDocument).

See my answer here for a sample.

+4
source

Read the section in the Swing tutorial on Implementing a document filter for working code that limits the number of characters in a text component.

The filter is preferable for the listener, since it does not allow updating the document. If you use a listener, you will need to discard the changes if the text exceeds your limit.

+3
source

Source: https://habr.com/ru/post/1300399/


All Articles