Make bad users behave by using JFC documents

How do you limit what a user can enter into a text field?

Q: I need to limit the number of characters that a user can enter into a text box. How do I prevent the user from entering too much data?

A: You can use custom documents to limit what a user inserts into a JTextField. Document is defined in the javax.swing.text package, and PlainDocument is the default Document for JTextField.

To limit the number of characters simply extend PlainDocument:

import javax.swing.text.*;
public class LimitDocument extends PlainDocument 
{
    private int limit;
    public LimitDocument(int limit) 
    {
        super();
    setLimit(limit);  // store the limit    
    }
    public final int getLimit() 
    {
    return limit;
    }
    public void insertString(int offset, String s, AttributeSet attributeSet) 
        throws BadLocationException 
    {
        if(offset < limit) // if we haven't reached the limit, insert the 
string
    {
        super.insertString(offset,s,attributeSet);
    } // otherwise, just lose the string
    }
    public final void setLimit(int newValue) 
    {
        this.limit = newValue;
    }
}

With the insertString() method, the only interesting method here, we can intercept the string before it appears in the JTextField. Here, we simply check to see if the user is trying to insert a character past the character limit specified in the constructor or set with setLimit().

Here is how you would use the document:

public static void main(String args[]) 
{
    JFrame f = new JFrame("Limit Test");
    JTextField text = new JTextField();
    text.setDocument(new LimitDocument(10));
            
    f.getContentPane().add(BorderLayout.NORTH,text);
    f.show();
}

The preceding main() method creates a JFrame and inserts a JTextField into it. The JTextField‘s document is set to an instance of our custom document. The document restricts the text field to 10 characters only.

The preceding code serves as a fairly simple example of using Swing documents. You can use documents to validate input as well as to format input, such as the date and time. For a good introduction to documents and Swing in general, see Resources.

Tony Sintes is a principal consultant at BroadVision. Tony, a Sun-certified Java 1.1 programmer and Java 2 developer, has worked with Java since 1997.

Source: www.infoworld.com