Tuesday, March 22, 2011

JTextField Validation

case 1: Int field (TextField can allow only numbers and length of numbers to be 5)

JTextField tfInt = new JTextField();

// Validation part
tfInt.setDocument( new PlainDocument() {
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException
{
if(str == null) return;
//accept only number
ch = str.charAt(0);
if (!((ch >47)&&(ch<58))) {
return;
}

// For length validation
if(offs > 4) return;
// While copy paste then below length validation required
if(str.length()>5) return;
super.insertString(offs, str, a);
}
});


// For Number validation
public class OnlyNumberValidator extends javax.swing.text.PlainDocument {
@Override
public void insertString(int offs, String str,
javax.swing.text.AttributeSet a)
throws javax.swing.text.BadLocationException {
StringBuffer buf = new StringBuffer(str);
int size = buf.length();
char c;
for (int i = 0; i < size; i++) {
c = buf.charAt(i);
if (!Character.isDigit(c)) {
buf.deleteCharAt(i);
}
}

super.insertString(offs, buf.toString(), a);
}
}

No comments:

Post a Comment