Quick Snippets: Filter JTextField Data

July 26th, 2006 § 1

Java makes it real easy to limit the data type of a JTextField with documents. Java allows you to set different documents that will validate user inputed data on the fly. For example in an options dialog, it is common to see a field that will only allow numerical inputs. This technique can be accomplished with a simple class and one line of code to implement that class.

[java]public class NumericDocument extends PlainDocument
{
// Variables
// — Private
private int m_nMaxLength;
private static final int MAX_LENGTH = 2;

public NumericDocument()
{
m_nMaxLength = 999999999;
}

public NumericDocument(int nMaxLength)
{
m_nMaxLength = nMaxLength;
}

// Insert string
public void insertString(int nOffset, String strString, AttributeSet aAttributes) throws BadLocationException
{
// Replace
strString = strString.replaceAll(“[^0-9]“, “”);

// Contruct
super.insertString(nOffset, strString, aAttributes);
}
}[/java]

And to implement with your JTextField

[java]
JTextField m_ctlTxtOption;

m_ctlTxtOption.setDocument(new NumericDocument());
[/java]

This technique can be extended and you can customize the data validation to your liking. Lets say you wanted a JTextField without any spaces allowed in it, you could use this line of code to validate the document data:

[java]
strString = strString.replaceAll(” “, “”);
[/java]

§ One Response to “Quick Snippets: Filter JTextField Data”

What's this?

You are currently reading Quick Snippets: Filter JTextField Data at Code and Coffee.