首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将textfield输入限制为列数/与DocumentFilter冲突

将textfield输入限制为列数/与DocumentFilter冲突
EN

Stack Overflow用户
提问于 2013-09-26 20:45:44
回答 1查看 233关注 0票数 0

我有一个WWFormattedTextField:

代码语言:javascript
复制
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的代码:

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-27 14:33:27

我在看了this post之后才知道的

显然,我不必费心于那种笨重的面具,只需同时使用DocumentFilter :大写和限制输入。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19038368

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档