Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Created January 14, 2022 03:34
Show Gist options
  • Save RustyKnight/d884f841b655ebf7e6e02ca762b13efb to your computer and use it in GitHub Desktop.
Save RustyKnight/d884f841b655ebf7e6e02ca762b13efb to your computer and use it in GitHub Desktop.
A document filter which can change the case of the input to either upper or lower case
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
// Original source https://tips4java.wordpress.com/2009/10/18/chaining-document-filters/
public class CaseModificationDocumentFilter extends ChainedDocumentFilter {
public enum Case {
UPPER, LOWER
}
private Case desiredCase;
/**
* Standard constructor for stand alone usage
*/
public CaseModificationDocumentFilter(Case desiredCase) {
this(null, desiredCase);
}
/**
* Constructor used when further filtering is required after this filter
* has been applied.
*/
public CaseModificationDocumentFilter(DocumentFilter filter, Case desiredCase) {
super(filter);
this.desiredCase = desiredCase;
}
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
replace(fb, offs, 0, str, a);
}
public void replace(FilterBypass fb, final int offs, final int length, String text, final AttributeSet a) throws BadLocationException {
if (text != null) {
switch (getDesiredCase()) {
case UPPER:
text = text.toUpperCase();
break;
case LOWER:
text = text.toLowerCase();
break;
}
super.replace(fb, offs, length, text, a);
}
}
public Case getDesiredCase() {
return desiredCase;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment