【发布时间】:2016-03-10 16:40:15
【问题描述】:
我正在使用 Java swing 程序。我想在我的 JPanel 中插入一个具有限制字符数的 JTextFieldFormat,并将所有文本转换为 UPPER 文本。 所以我已经构建了这段代码:
textCodiceFiscale = new JTextField();
textCodiceFiscale.setDocument(new PersonalizzaJtextField(numberCharacter));
DocumentFilter filter = new UppercaseDocumentFilter();
((AbstractDocument) textCodiceFiscale.getDocument()).setDocumentFilter(filter);
这是 UppercaseDocumentFilter 类:
class UppercaseDocumentFilter extends DocumentFilter {
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attr) throws BadLocationException {
fb.insertString(offset, text.toUpperCase(), attr);
}
public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
fb.replace(offset, length, text.toUpperCase(), attrs);
}
}
这是 PersonalizzaJTextField 类:
public class PersonalizzaJtextField extends PlainDocument {
//private StringBuffer cache = new StringBuffer();
private int lunghezzaMax;
public PersonalizzaJtextField(int lunghezzaMax){
super();
this.lunghezzaMax = lunghezzaMax;
}
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException{
if (str == null)
return;
if ((getLength() + str.length()) <= lunghezzaMax) {
super.insertString(offset, str, attr);
}
}
}
现在有两个问题:
1) 使用此代码,我只能在 JTextField 中插入 UPPER 字符,但我在第二行限制字符数,不起作用。
2)我想为这个JTextField创建一个模板,我必须在这个模式下插入数字或文本:
6 个字符 2 个数字 1 个字符 2 个数字 1 个字符 3 个数字 1 个字符。
可以这样做吗?
【问题讨论】:
-
不要使用自定义文档!!!只需使用
DocumentFilter并将这两个条件组合到过滤器中。首先你检查尺寸。如果更大,则退出。否则,在插入之前将文本转换为大写。
标签: java swing jtextfield documentfilter