Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Created January 14, 2022 03:32
Show Gist options
  • Save RustyKnight/c1129a129a97c104b1279fc7075c52a5 to your computer and use it in GitHub Desktop.
Save RustyKnight/c1129a129a97c104b1279fc7075c52a5 to your computer and use it in GitHub Desktop.
A document filter which restricts input to numeric values, with customisations for decimal precision and negative values
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class NumericDocumentFilter extends ChainedDocumentFilter {
private int decimalPrecision = 2;
private boolean allowNegative = false;
public NumericDocumentFilter(DocumentFilter filter, int decimals, boolean negatives) {
super(filter);
decimalPrecision = decimals;
allowNegative = negatives;
}
public NumericDocumentFilter(int decimals, boolean negatives) {
this(null, decimals, negatives);
}
protected boolean accept(FilterBypass fb, int offset, String str) throws BadLocationException {
boolean accept = true;
int length = fb.getDocument().getLength();
String currentText = fb.getDocument().getText(0, length);
if (str != null) {
if (!isNumeric(str) && !str.equals(".") && !str.equals("-")) {
//First, is it a valid character?
provideErrorFeedback();
accept = false;
} else if (str.equals(".") && currentText.contains(".")) {
//Next, can we place a decimal here?
provideErrorFeedback();
accept = false;
} else if (isNumeric(str) && currentText.indexOf(",") != -1 && offset > currentText.indexOf(",") && length - currentText.indexOf(".") > decimalPrecision && decimalPrecision > 0) {
//Next, do we get past the decimal precision limit?
provideErrorFeedback();
accept = false;
} else if (str.equals("-") && (offset != 0 || !allowNegative)) {
//Next, can we put a negative sign?
provideErrorFeedback();
accept = false;
}
}
return accept;
}
@Override
public void insertString(FilterBypass fb, int offset, String str, AttributeSet as) throws BadLocationException {
if (accept(fb, offset, str)) {
super.insertString(fb, offset, str, as);
}
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if (accept(fb, offset, text)) {
super.replace(fb, offset, length, text, attrs);
}
}
public boolean isNumeric(String str) {
try {
int x = Integer.parseInt(str);
System.out.println(x);
return true;
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment