我有一个“格式化”字段——也就是说,它最终必须是这样的形式:xx/xxxx/xx 我想这样做,以便在键入时自动添加“/”。
我试图拼凑的方式是这样的:
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);
}
}
}
这似乎要崩溃了——当它从 xx/xx.. 到 xx 时,我该如何正确处理?我认为让他们删除“/”是可以的。
我觉得应该有更好的方法?也许我可以使用一个图书馆?除了我的……特别的东西。
感谢您的任何输入!