LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Java JTextArea - limiting amount of characters entered (http://www.linuxquestions.org/questions/programming-9/java-jtextarea-limiting-amount-of-characters-entered-155469/)

Andy@DP 03-09-2004 01:09 PM

Java JTextArea - limiting amount of characters entered
 
I have an app I'm working on that uses Swing GUI components and need to limit the character length of a JTextArea. I know I can override the keydown() method of the Component class (i think) to check length of inputted text before allowing a character to be written to screen but I wondered if there was an easier way to do this.

I have scoured the Java API and come up with nothing.

TIA,
Andy.

Looking_Lost 03-09-2004 02:23 PM

There's info on it on suns Java Trail site here

Implementing Document Filter

Looks like you get the Document model associated with the JTextArea ( PlainDocument) and cast to AbastractDocument and create/set your own DocumentFilter for the JTextArea
The code is there in the DocumentFilter link on that page. You could use the class example provided and implement it something like this for a JTextArea


int maxChars=10;

JTextArea tArea=new JTextArea();


AbstractDocument pDoc=(AbstractDocument)tArea.getDocument();

pDoc.setDocumentFilter(new DocumentSizeFilter(maxChars));

Andy@DP 03-09-2004 03:46 PM

Thanks Looking_Lost,
That link has inspired me to a workable solution! :)

Good tae get a straight answer fae a fellow Scot!

german 03-10-2004 01:16 AM

You can do lots of cool stuff with JTextArea's by creating custom Document classes like this (I haven't even compiled this code but it should work)... just do jTextField.setDocument(new CustomDocument(jTextField));

Code:


static class CustomDocument extends PlainDocument {
  private static int MAX_LENGTH = 50;
  private JTextArea tField;

  UpperCaseDocument(JTextArea field) {
    tField = field;
  }

  public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {

    if(str == null | | tField.getText().length() > MAX_LENGTH)
      return;

    super.insertString(offs, str, a);
  }
}

HTH

B.


All times are GMT -5. The time now is 03:44 PM.