Take a look at the following code snippet which overrides the text field's
plain document class to perform input validation at the input buffer level:
A)Make sure to import javax.swing.text.*;
B)Then, create either an inner class or a friendly class as follows:
class NumericDocument extends PlainDocument
{
public void insertString(int offs, String str, AttributeSet attr)
{
int length=str.length();
boolean ok=true;
for (int i=0; ok && i < length; i++)
{
char ch = str.charAt(i);
ok = (ch == '.' || ch == '-' || Character.digit(ch, 10) >= 0);
//this will only allow input of whole numbers neg or pos:
//ok = (ch == '-' || Character.digit(ch, 10) >= 0);
//...and this would only allows for whole numbers:
//ok = (Character.digit(ch, 10) >= 0);
}
if (ok)
try
{
super.insertString(offs, str, attr);
}
catch (BadLocationException e)
{
}
else
{
Toolkit.getDefaultToolkit().beep();
}
}
} /* END OF CLASS NUMERIC DOCUMENT */
C) Last, change the construction of the text field to the following line:
JTextField jTextQty = new JTextField( new NumericDocument(),"1",0);
You could easily extend this to limit the number of characters to allow in
the input.
-----Original Message-----
From: A mailing list about Java Server Pages specification and reference
[mailto:[EMAIL PROTECTED]]On Behalf Of rajac
Sent: Thursday, January 17, 2002 10:32 PM
To: [EMAIL PROTECTED]
Subject: validation
Hi,
I am using Swing as GUI. I want to validate the text field in such a way
that the user should not be able to enter more than 5 characters. Is there
any direct way of doing this?.
Regards,
Raja
===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
For digest: mailto [EMAIL PROTECTED] with body: "set JSP-INTEREST DIGEST".
Some relevant FAQs on JSP/Servlets can be found at:
http://archives.java.sun.com/jsp-interest.html
http://java.sun.com/products/jsp/faq.html
http://www.esperanto.org.nz/jsp/jspfaq.jsp
http://www.jguru.com/faq/index.jsp
http://www.jspinsider.com