My problem is as follows:
I have a:
public class WWFormattedTextField extends JFormattedTextField implements FocusListener {
All of the formatted textfields on all the screens will always be uppercase. We want them appear upper case while typing, etc. So here is what we did for that:
public class WWFormattedTextField extends JFormattedTextField implements FocusListener {
private DocumentFilter filter = new UppercaseDocumentFilter();
private boolean isEmail = false;
public WWFormattedTextField() {
super();
init();
}
private void init() {
addFocusListener(this);
((AbstractDocument) this.getDocument()).setDocumentFilter(filter);
}
public void setIsEmail(boolean email) {
//Normally this is where I would put something like
//if email is true - allow mixed case characters
this.isEmail = email;
}
public boolean getIsEmail() {
return isEmail;
}
Now all of the WWFormattedTextFields on all screens are typed in upper case characters. Here is the UppercaseDocumentFilter() mentioned earlier:
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);
}
}
As you can see, this FormattedTextField also has an isEmail property. When that value is true - I want to allow user to enter mixed case characters into the field, but only that specific one.
Any hints/suggestions on how I can do that?
Add an isEmail
property to UppercaseDocumentFilter
so that specific filters can produce uppercase text
public class UppercaseDocumentFilter extends DocumentFilter {
private boolean isEmail;
public UppercaseDocumentFilter(boolean isEmail) {
this.isEmail = isEmail;
}
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
fb.insertString(offset, isEmail? text: text.toUpperCase(), attr);
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
fb.replace(offset, length, isEmail? text: text.toUpperCase(), attrs);
}
}
then set the filter like this
DocumentFilter filter = new UppercaseDocumentFilter(isEmail);
((AbstractDocument) this.getDocument()).setDocumentFilter(filter);