Friday, January 2, 2009

How to create TextField that only accept letter (Java)

If you use a normal JTextField then all character(s) can be accepted. But sometimes we need a textfield that only accept letter ('a'-'z' and 'A'-'Z').
I Hope this JLetterField.java can solve your problem.


import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

public class JLetterField
extends JTextField
{
public JLetterField(int cols) {
super("",cols);
}

protected Document createDefaultModel() {
return new LetterDocument();
}

class LetterDocument extends PlainDocument {
public void insertString(int offs,String str,AttributeSet a)
throws BadLocationException
{
if(str==null) return;
char [] before = str.toCharArray();
String after = "";
for(int i=0;i < before.length;i++)
{
if( (before[i]>='a' && before[i]<='z') || (before[i]>='A' && before[i]<='Z') )
after += before[i];
}
super.insertString(offs,after,a);
}
}
}

3 comments:

  1. This program there is one that is wrong

    For (int i=0;i

    There was no sign ")" to close him came back... Please to be improved

    ReplyDelete
  2. Thanks for your comment. It's fixed now.

    ReplyDelete