I have a ‘formatted’ field – that is that it must be finally in a form like this: xx/xxxx/xx
I’d like to make it so that while typing you get the ‘/’ added automatically.
The way that I am trying to cobble together is something like this:
JTextField field = new JTextField ("xx/xxxx/xx");
// a focus listener to clear the "xx/xxxx/xx" on focus & restore on focus-out
// the override the 'document' with this:
field.setDocument (new PlainDocument () {
public void insertString (int off, String str, AttributeSet attr) throws BadLocationException {
if (off == 2 || off == 7) {
super.insertString (off + 1, str + "/", attr);
}
}
}
This seems like it is going to break – and how do I properly deal with when it goes from: xx/xx.. to xx? I think having them delete the ‘/’ is ok.
I feel there should be a better way? Maybe a library I could use? Something other than my…special stuff.
Thanks for any input you have!!
To achieve this I did this:
This is different that the other solution in that the ‘/’ doesn’t exist when there is no text, it is added at the right places. It doesn’t currently doesn’t deal with any of the replacement stuff — eh. :/