set jtextfield textlimit and uppercase at same time

房东的猫 提交于 2019-12-11 13:59:27

问题


I Have a couple jtextfield in my app and I want to put one of them that allow upper and lowcase and also put the limit of number of character that can be introduce into the jtextfield. I have to separe class, one to put the limit and the other to put the upper or lowcase.

code to the limit of jtextfield:

package tester;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class TextLimiter extends PlainDocument {

    private Integer limit;

    public TextLimiter(Integer limit) {
        super();
        this.limit = limit;
    }

    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if (str == null) {
            return;
        }
        if (limit == null || limit < 1 || ((getLength() + str.length()) <= limit)) {
            super.insertString(offs, str, a);
        } else if ((getLength() + str.length()) > limit) {
            String insertsub = str.substring(0, (limit - getLength()));
            super.insertString(offs, insertsub, a);
        }
    }
}

and here is the code to set uppercase or vice versa:

package classes;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class upperCASEJTEXTFIELD 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);
    }
}

to resume my question, I want to set a jtextfield limit = 11 and uppercase.


回答1:


PlainDocument doc = new TextLimiter();
doc.setDocumentFiletr(new upperCASEJTEXTFIELD());
JTextField textField = new JTextField();
textField.setDocument(doc);



回答2:


I have to separe class, one to put the limit and the other to put the upper or lowcase.

Why do you need separate classes? Just because you happened to find examples on the web that use two different classes doesn't mean you need to implement your requirement that way.

You can easily combine the logic of both classes into one DocumentFilter class.

Or, if you want to get a little fancier you can check out Chaining Document Filters which shows how you might combine individual document filters into one.



来源:https://stackoverflow.com/questions/15641833/set-jtextfield-textlimit-and-uppercase-at-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!