将文本字段输入限制为列数/与DocumentFilter冲突

时间:2013-09-26 20:45:44

标签: java netbeans maskedtextbox jformattedtextfield documentfilter

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

1 个答案:

答案 0 :(得分:0)

我在阅读this post

之后想出来了

显然我不必为那个笨重的面具而烦恼,只需使用DocumentFilter:大写和限制输入。