Thursday, February 23, 2012

Setting Maximum no. of characters in jTextField for Swing Application

Sometimes we need to fixed the maximum size of a text field. For this purpose, we need to implement a document containing an overriding function of plain document.

public class MaxLengthTextDocument extends PlainDocument {

private int maxChars;

@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if(str != null && (getLength() + str.length() < getMaxChars())){ super.insertString(offs, str, a); } } /** * @return the maxChars */ public int getMaxChars() { return maxChars; } /** * @param maxChars the maxChars to set */ public void setMaxChars(int maxChars) { this.maxChars = maxChars; } }



after that we will have to set the following line after initComponents() of view file.


MaxLengthTextDocument maxLength = new MaxLengthTextDocument();
maxLength.setMaxChars(12);//50 is a maximum number of character
this.txtMobileNo.setDocument(maxLength);

No comments: