Java Swing - O Reilly strategy only catches keyboard
Wednesday, October 31st, 2007Java Swing - O Reilly strategy only catches keyboard entry. All you need is an extension of PlainDocument that overrides the insertString() method, to verify that the requested insertion is valid. Here’s a class that limits the number of characters in the field: // FixedLengthPlainDocument.java // import java.awt.Toolkit; import javax.swing.*; import javax.swing.text.*; // An extension of PlainDocument that restricts the length of the content it // contains. public class FixedLengthPlainDocument extends PlainDocument { // Create a new document with the given max length public FixedLengthPlainDocument(int maxLength) { this.maxLength = maxLength; } // If this insertion would exceed the maximum document length, we “beep” and do // nothing else. Otherwise, super.insertString() is called. public void insertString(int offset, String str, AttributeSet a) throws BadLocationException { if (getLength() + str.length() > maxLength) { Toolkit.getDefaultToolkit().beep(); } else { super.insertString(offset, str, a); } } private int maxLength; } To use this class, simply pass in an instance of it to the JTextField constructor. Or, if you plan on using this document type for many text fields, you might want to create a new subclass of JTextField. Here’s an example: // FixedLengthTextField.java - 646
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.