X-Git-Url: http://gitweb.fperrin.net/?p=GpsPrune.git;a=blobdiff_plain;f=src%2Ftim%2Fprune%2Fgui%2FDecimalNumberField.java;fp=src%2Ftim%2Fprune%2Fgui%2FDecimalNumberField.java;h=39c55d4ecaf0d4b29be10647adfe604f83acbc3b;hp=0000000000000000000000000000000000000000;hb=ce6f2161b8596f7018d6a76bff79bc9e571f35fd;hpb=2d8cb72e84d5cc1089ce77baf1e34ea3ea2f8465 diff --git a/src/tim/prune/gui/DecimalNumberField.java b/src/tim/prune/gui/DecimalNumberField.java new file mode 100644 index 0000000..39c55d4 --- /dev/null +++ b/src/tim/prune/gui/DecimalNumberField.java @@ -0,0 +1,110 @@ +package tim.prune.gui; + +import java.awt.Dimension; + +import javax.swing.JTextField; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.PlainDocument; + +/** + * text field for holding a decimal number with validation + * - doesn't allow certain characters such as a-z to be entered + */ +public class DecimalNumberField extends JTextField +{ + /** + * Inner class to act as document for validation + */ + protected static class DecimalNumberDocument extends PlainDocument + { + private boolean _allowNegative = false; + + /** constructor */ + DecimalNumberDocument(boolean inAllowNegative) { + _allowNegative = inAllowNegative; + } + + /** + * Override the insert string method + * @param offs offset + * @param str string + * @param a attributes + * @throws BadLocationException on insert failure + */ + public void insertString(int offs, String str, AttributeSet a) + throws BadLocationException + { + char[] source = str.toCharArray(); + char[] result = new char[source.length]; + int j = 0; + for (int i = 0; i < result.length; i++) { + if (!Character.isLetter(source[i]) && (_allowNegative || source[i] != '-') && source[i] != ' ') // no letters, no minus sign or space + result[j++] = source[i]; + } + super.insertString(offs, new String(result, 0, j), a); + } + } + + + /** + * Constructor + */ + public DecimalNumberField() + { + this(false); + } + + /** + * Constructor + * @param inAllowNegative true to allow negative numbers + */ + public DecimalNumberField(boolean inAllowNegative) + { + super(6); + setDocument(new DecimalNumberDocument(inAllowNegative)); + } + + /** + * @return double value + */ + public double getValue() + { + return parseValue(getText()); + } + + /** + * @param inValue value to set + */ + public void setValue(double inValue) + { + setText("" + inValue); + } + + /** + * @param inText text to parse + * @return value as double + */ + private static double parseValue(String inText) + { + double value = 0.0; + try { + value = Double.parseDouble(inText); + } + catch (NumberFormatException nfe) {} + if (value < 0) { + value = 0; + } + return value; + } + + /** + * Put a minimum on the minimum width + */ + public Dimension getMinimumSize() + { + Dimension dim = super.getMinimumSize(); + if (dim.width < 50) dim.width = 50; + return dim; + } +}