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.
PlainDocument doc = new TextLimiter();
doc.setDocumentFiletr(new upperCASEJTEXTFIELD());
JTextField textField = new JTextField();
textField.setDocument(doc);