views:

242

answers:

3

Hi!,

I'm developing an application which requires that only 165 characters to be in the JTextArea. I've imposed that condition. I've used a static counter for counting number of characters entered in the textarea and also coded to handle the condition when user deletes any string from the text the counter must be incremented by considering length of the string selected.

However now I want to handle the condition when user performs 'cut' or 'paste' option by pressing 'Ctrl+X' and 'Ctrl+V'. I know that default methods from JTextComponent are inherited in JTextArea but I want to get the cut text and know the length of the cut text so as to decrement the counter maintained for characters and increment it while pasting by appropriate amount.

+2  A: 

It sounds like you need to use DocumentListener to track the changes. The events in the document listener will tell you how many characters are added/removed in any given change, and also gives you a reference to the Document that is backing the text area.

The following is an example document listener implementation 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 cut and pastes as well as key presses.

Ash
Thank you a lot! :) The problem is finally solved!!!
Supereme
+4  A: 

Create a DocumentFilter and set it on a new PlainDocument. Use this document to create the JTextArea. (Or use the default document of the JTextArea, after casting to AbstractDocument).

See my answer here for a sample.

Carlos Heuberger
+3  A: 

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

A filter is preferable to a listener because it prevents the Document from being updated. If you use a listener you will need to undo changes when the text exceeds your limit.

camickr