Java PlainDocument limit document length

Description

Java PlainDocument limit document length

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

public class Main {
   public static void main(String[] args) {
      JTextField textfield1 = new JTextField(15);
      textfield1.setDocument(new JTextFieldLimit(10));

      JFrame frame = new JFrame("UpcaseFilter");
      frame.getContentPane().add(textfield1, java.awt.BorderLayout.NORTH);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(200, 120);//from  w  ww . j  a v a 2 s  . co m
      frame.setVisible(true);
   }
}

class JTextFieldLimit extends PlainDocument {
   private int limit;

   JTextFieldLimit(int limit) {
      super();
      this.limit = limit;
   }

   public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
      if (str == null)
         return;

      if ((getLength() + str.length()) <= limit) {
         super.insertString(offset, str, attr);
      }
   }
}



PreviousNext

Related