Re: TextField error checking

From: Todd Corley (todd.corley_at_rulespower.com)
Date: 12/22/03


Date: 22 Dec 2003 13:21:59 -0800

Look into javax.swing.text.DocumentFilter.

It lets you do realtime editing to to changes in the document with out
worrying about firing yourself into an event loop.
 
Below will work for you, just add it like

yourTextField.getDocument().addDocumentFilter( new MFilter() );

Good Luck,
Todd

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;

public class MFilter extends DocumentFilter
{

    public void insertString(DocumentFilter.FilterBypass fb,
                             int offset,
                             String string,
                             AttributeSet attr) throws
BadLocationException
    {

        fb.insertString(offset, string, attr);
        if( !validate( fb.getDocument() ) )
        {
            fb.remove(offset,string.length());
        }
    }

    public void remove(DocumentFilter.FilterBypass fb,
                       int offset,
                       int length) throws BadLocationException
    {

        String orig = fb.getDocument().getText(offset,length);
        fb.remove(offset, length);
        if( !validate( fb.getDocument() ) )
        {
            fb.insertString(offset,orig,null);
        }
    }

    public void replace(DocumentFilter.FilterBypass fb,
                        int offset,
                        int length,
                        String text,
                        AttributeSet attrs) throws
BadLocationException
    {
        String orig = fb.getDocument().getText(offset,length);
        text = text.toUpperCase();
        fb.replace(offset, length, text, attrs);
        if( !validate( fb.getDocument() ) )
        {
            if( orig.equals( "" ) )
            {
                fb.remove(offset,text.length());
            }
            else
            {
                fb.replace(offset, length, orig, attrs);
            }
        }
    }

    public boolean validate(Document doc )
    {
        boolean retVal = true;

        String text = "";
        try
        {
            text = doc.getText(0, doc.getLength() );
        }
        catch( Exception e )
        {
        }
        int len = text.length();
        if( len > 4 )
        {
            return( false );
        }
        if( len > 1 )
        {
            try
            {
                int val = Integer.valueOf( text.substring(1)
).intValue();
                retVal = val > 0 && val <= 110;
            }
            catch( Exception exc )
            {
                retVal = false;
            }
        }
        retVal = (text.charAt(0) == 'M' && retVal );
        return retVal;
    }
}