Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top