I tried putting together custom PlainDocument made by others for one I needed, but since I don't know the mechanics of PlainDocument, I failed and it didn't work. I need something that will make sure my textfield only allows 2 letters, so anything a-zA-Z that occurs only twice. I tried this first:
public class LetterDocument extends PlainDocument {
private String text = "";
@Override
public void insertString(int offset, String txt, AttributeSet a) {
try {
text = getText(0, getLength());
if ((text + txt).matches("^[a-zA-Z]{2}$")) {
super.insertString(offset, txt, a);
}
} catch (Exception ex) {
Logger.getLogger(LetterDocument.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This doesn't even let me type in anything. I then tried this, which I tried putting together from two other threads, one of them letting only letters be typed in, and the other limiting the characters:
public class LetterDocument extends PlainDocument {
private int limit;
private String text = "";
LetterDocument(int limit) {
super();
this.limit = limit;
}
@Override
public void insertString(int offset, String txt, AttributeSet a)
throws BadLocationException {
if (txt == null)
return;
try {
text = getText(0, getLength());
if (((text + txt).matches("[a-zA-Z]"))
&& (txt.length()) <= limit) {
super.insertString(offset, txt, a);
}
} catch (Exception ex) {
Logger.getLogger(LetterDocument.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
I have no idea what's wrong.
Don't use a custom Document.
Instead use a DocumentFilter
. Read the section from the Swing tutorial on Implementing a Document Filter for a working example that limits the number of characters you can enter in a Document.
Then just add some additional logic to make sure only letters are added.
Or an easier option is to use a JFormatttedTextField with a character mask. Again see the tutorial on Using a Formatted Text Field.