Limiting the Capacity of a JTextComponent using custom Document - Java Swing

Java examples for Swing:JTextComponent

Description

Limiting the Capacity of a JTextComponent using custom Document

Demo Code


import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;

public class Main {
  public static void main(String[] args) throws Exception {
    JTextComponent textComp = new JTextField();
    textComp.setDocument(new FixedSizePlainDocument(10));
  }// w ww.  ja  va 2 s  .co m
}

class FixedSizePlainDocument extends PlainDocument {
  int maxSize;

  public FixedSizePlainDocument(int limit) {
    maxSize = limit;
  }

  public void insertString(int offs, String str, AttributeSet a)
      throws BadLocationException {
    if ((getLength() + str.length()) <= maxSize) {
      super.insertString(offs, str, a);
    } else {
      throw new BadLocationException("Insertion exceeds max size of document",
          offs);
    }
  }
}

Related Tutorials