我有一个 WWFormattedTextField:
public class WWFormattedTextField extends JFormattedTextField implements FocusListener {
private DocumentFilter filter = new UppercaseDocumentFilter();
private boolean limitToMaxInput = false;
public WWFormattedTextField() {
super();
init();
}
private void init() {
addFocusListener(this);
//This line makes ALL text in ALL textfields uppercase as they type
((AbstractDocument) this.getDocument()).setDocumentFilter(filter);
}
//This method uses value of colulmn property of textfield and creates a mask
//that limits the amount of characters
public void setLimitToMaxInput(boolean limitToMaxInput) {
int columns = getColumns();
String patternLimit = "";
while (columns > 0) {
patternLimit = patternLimit.concat("*");
columns -= 1;
}
try {
setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter(patternLimit)));
} catch (ParseException ex) {
Logger.getLogger(WWFormattedTextField.class.getName()).log(Level.SEVERE, null, ex);
}
this.limitToMaxInput = limitToMaxInput;
}
我的问题是 setLimitToMaxInput 覆盖了 UppercaseDocumentFilter。该字段仅限于列数,但因为掩码是 * - 当用户键入时 - 它不会大写它......
需要一些有用的提示或建议来实现我的目标的正确方法:一个总是大写的文本字段,当达到最大大小(列)时限制(停止)用户输入。
UppercaseDocumentFilter 的代码:
public class UppercaseDocumentFilter extends DocumentFilter{
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
fb.insertString(offset, text.toUpperCase(), attr);
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
fb.replace(offset, length, text.toUpperCase(), attrs);
}
}