1
package pipe.gui.widgets;
3
import java.text.DecimalFormatSymbols;
4
import java.util.regex.Matcher;
5
import java.util.regex.Pattern;
7
import javax.swing.text.AttributeSet;
8
import javax.swing.text.BadLocationException;
9
import javax.swing.text.DocumentFilter;
11
public class DecimalOnlyDocumentFilter extends DocumentFilter{
13
int numberOfDecimalPlaces;
15
public DecimalOnlyDocumentFilter() {
19
public DecimalOnlyDocumentFilter(int numberOfDecimalPlaces){
20
this.numberOfDecimalPlaces = numberOfDecimalPlaces;
24
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
25
//this method is only called by programmatic editing of the text box!
29
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
30
String old = fb.getDocument().getText(0, fb.getDocument().getLength());
31
StringBuffer newString = new StringBuffer(old);
32
newString.replace(offset, length+offset, "");
33
if (stringIsValidDecimal(newString.toString())) {
34
super.remove(fb, offset, length);
39
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
40
String old = fb.getDocument().getText(0, fb.getDocument().getLength());
41
StringBuffer newString = new StringBuffer(old);
42
newString.replace(offset, length+offset, text);
43
if (stringIsValidDecimal(newString.toString())) {
44
super.replace(fb, offset, length, text, attrs);
47
private boolean stringIsValidDecimal(String text) {
48
char localDecimalseparator = DecimalFormatSymbols.getInstance().getDecimalSeparator();
49
Pattern pattern = Pattern.compile("^(([1-9]([0-9])*)?|0)(" + Pattern.quote(Character.toString(localDecimalseparator)) + "([0-9]*))?$");
50
Matcher m = pattern.matcher(text);
51
return m.matches() && (numberOfDecimalPlaces < 0 || m.group(5) == null || m.group(5).length() <= numberOfDecimalPlaces);