我有一个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);
}
}