I have a WWFormattedTextField:
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;
}
My problem is that the setLimitToMaxInput overwrites the UppercaseDocumentFilter. The field is limited to number of columns, but because the mask is * - when user types - it doesn't uppercase it...
Need some helpful hints or suggestions towards the correct way to achieve my goal: an always upprercase textfield that limits(stops) user input when max size (columns) is reached.
Code for the UppercaseDocumentFilter:
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);
}
}
I figured it out after reading this post
Apparently I didn't have to bother with that clunky mask and just use DocumentFilter for both: uppercase and limiting input.