1

How can i limit the number of characters in JTextArea row, and make it skip to the second one?

2
  • I'm assuming that you're using Swing and a JTextArea, but on re-reading your question I could be wrong. Is this for Swing? AWT? Android? Other? Dec 4, 2011 at 17:28
  • question, you can set the Limit, but there are my questions --> , if you'll touch the limit what will be happening 1) any new Chars will be added, 2) by removing from begining, 3) by removing from end, three choises there are, because text can be append() or insert()
    – mKorbel
    Dec 4, 2011 at 18:12

2 Answers 2

10

If you're using Swing and a JTextArea, try using the setWrapStyleWord and setLineWrap methods:

  textarea.setWrapStyleWord(true);
  textarea.setLineWrap(true);

You'll also want to set the column count of the JTextArea:

private static final int TA_ROWS = 20;
private static final int TA_COLS = 35;

private JTextArea textarea = new JTextArea(TA_ROWS, TA_COLS);

and wrap the JTextArea in a JScrollPane of course.

Edit
I'm assuming that you're using Swing, but on re-reading your question I could be wrong. Is this for Swing? AWT? Android? Other?

1
  • 1
    It's for Swing. Thank you for the answer, it was very useful. Dec 4, 2011 at 17:29
1

Somehow the above solution didnt work for me. I instead used a DocumentFilter like below:

public class StockPublicNotesDocumentFilter extends DocumentFilter {  

 private final int maxLength;

 public StockPublicNotesDocumentFilter (int maxLength) {  
     this.maxLength = maxLength;
 }  

 /** 
  * {@inheritDoc} 
  */  

 public void insertString (DocumentFilter.FilterBypass fb, int offset, String str, AttributeSet attr)  
         throws BadLocationException {
     if ((fb.getDocument().getLength() + str.length()) <= this.maxLength)
            super.insertString(fb, offset, str, attr);
        else
            Toolkit.getDefaultToolkit().beep();
 }  

 /** 
  * {@inheritDoc} 
  */  

 public void replace (DocumentFilter.FilterBypass fb, int offset, int length, String str, AttributeSet attrs) throws BadLocationException {
     if ((fb.getDocument().getLength() + str.length()) <= this.maxLength)
            super.replace(fb, offset, length, str, attrs);
        else
            Toolkit.getDefaultToolkit().beep();

 }
}

This will be called as

JTextArea comment = componentFactory.generateTextArea(stock.getComment());

StockPublicNotesDocumentFilter publicNotesfilter = new StockPublicNotesDocumentFilter(PUBLIC_NOTES_MAX_CHARS);
        ((PlainDocument) comment.getDocument()).setDocumentFilter(publicNotesfilter);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.