An extension of PlainDocument that restricts the length of its content : Document Event « Swing JFC « Java






An extension of PlainDocument that restricts the length of its content

An extension of PlainDocument that restricts the length of its content
   


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

public class MaxLengthDocument extends PlainDocument {
  private int max;

  public MaxLengthDocument(int maxLength) {
    max = maxLength;
  }

  public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
    if (getLength() + str.length() > max)
      java.awt.Toolkit.getDefaultToolkit().beep();
    else
      super.insertString(offset, str, a);
  }

}

class MainClass{
  public static void main(String[] a){
      Document doc = new MaxLengthDocument(5); // set maximum length to 5
      JTextField field = new JTextField(doc, "", 8);

      JPanel flowPanel = new JPanel();
      flowPanel.add(field);
      JFrame frame = new JFrame("MaxLengthDocument demo");
      frame.setContentPane(flowPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(160, 80);
      frame.setVisible(true);
  }
}
           
         
    
    
  








Related examples in the same category

1.DocumentFilter that maps lowercase letters to uppercaseDocumentFilter that maps lowercase letters to uppercase
2.Document Event DemoDocument Event Demo
3.React to the document update insert changed eventReact to the document update insert changed event
4.HTMLDocument: Document Iterator Example
5.DocumentListener DemoDocumentListener Demo
6.extends PlainDocument to create a float value type text field
7.extends PlainDocument to create alpha and numeric value based field field
8.Implement a document cleaner that maps lowercase letters to uppercaseImplement a document cleaner that maps lowercase letters to uppercase
9.Document ElementIterator DemoDocument ElementIterator Demo
10.Format JTextField's text to uppercase
11.Overriding a Few Default Typed Key Bindings in a JTextComponent
12.Overriding - key
13.Override $ key
14.Overriding space key
15.Disable a character so that no action is invoked.
16.Bind a keystroke to shift-space
17.Prevent the space from being inserted when shift-space is pressed.
18.Subclass InputVerifier
19.extends PlainDocument
20.This Document restricts the size of the contained plain text to the given number of characters.
21.A frame with three text fields to set the background color.