I am trying to validate percentage value from JformattedTextField. I am using Regular Expression to validate the input. I am setting regex in JFormattedTextField to validate input while user is typing itself.
i.e I should restrict that user should not type more than 100.
Regex what i am currently using is
String m_strPercentageFormat = "[0-9]{0,2}\\.{0,1}[0-9]{0,2}";
JFormattedTextField percentTextField = new JFormattedTextField();
percentTextField.setDocument(new ValidateTextComponent(m_strPercentageFormat ));
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class ValidateTextComponent extends PlainDocument
{
private String m_strPattern;
private Pattern m_Pattern;
private Matcher m_Matcher;
private String m_strComponentText;
public ValidateTextComponent(String strPattern)
{
super();
this.m_strPattern = strPattern;
try
{
m_Pattern = Pattern.compile(m_strPattern);
}
catch (Exception e)
{
int numReaders = 0;
throw new PatternSyntaxException("Check the pattern", strPattern,
numReaders);
}
}
public void insertString(int iOffSet, String strChar, AttributeSet attSet)
throws BadLocationException
{
String strCharUpper = strChar.toUpperCase();
m_strComponentText = getText(0, iOffSet) +strCharUpper;
m_Matcher = m_Pattern.matcher(m_strComponentText);
if (m_Matcher.matches())
{
super.insertString(iOffSet, strCharUpper, attSet);
}
else
{
//TODO Toolkit.getDefaultToolkit().beep();
}
}
}
The problem is
1. It is allowing to enter more than 100
Message was edited by:
sathiq