001 package market; 002 003 /** 004 * A ValueChecker, which checks if a String is in the format of a Double (e.g. 15.256).<br> 005 * Notations like 15,256 are also allowed. The number must not be negative.<br> 006 * <br> 007 * As this ValueChecker is only used by {@link market.swing.JTFCheckable checkable text fields}, 008 * an identifier is passed via the constructor. This descriptive identifier is used in the error string, 009 * to enable the user to associate an error message with the causative text field. 010 */ 011 public class VCPositiveDouble implements ValueChecker { 012 013 /** 014 * The identifier used by {@link #getErrorString()}. 015 */ 016 protected String identifier; 017 018 /** 019 * Defines if an empty String is considered to be an error or not. 020 */ 021 protected boolean mayBeEmpty; 022 023 /** 024 * Internal error code. Set by {@link #isValidValue(String)}, queried by {@link #getErrorString()}. 025 */ 026 private int error; 027 028 /** 029 * @param identifier the identifier. 030 * @param mayBeEmpty <code>true</code> if an empty should be considered valid, otherwise <code>false</code>. 031 */ 032 public VCPositiveDouble(String identifier, boolean mayBeEmpty) { 033 this.identifier = identifier; 034 this.mayBeEmpty = mayBeEmpty; 035 } 036 037 /** 038 * @param identifier the identifier. 039 */ 040 public VCPositiveDouble(String identifier) { 041 this.identifier = identifier; 042 this.mayBeEmpty = false; 043 } 044 045 /** 046 * Checks String for validity and, if necessary, sets an internal error code according to the 047 * detected error. 048 * @param content the String to be checked. 049 * @return <code>true</code> if the String represents a Double, otherwise <code>false</code>. 050 */ 051 public boolean isValidValue(String content) { 052 error = 0; 053 if (!mayBeEmpty && content.equals("")) error = 1; 054 if (!content.equals("") && error == 0) { 055 if (Conversions.convertComma(content) == null) error = 2; 056 } 057 if (!content.equals("") && error == 0) { 058 if (Double.valueOf(Conversions.convertComma(content)).doubleValue() < 0) error = 3; 059 } 060 return error == 0; 061 } 062 063 /** 064 * @return an error message depending on the value of {@link #error}. 065 */ 066 public String getErrorString() { 067 String returnValue = ""; 068 switch (error) { 069 case 1: returnValue = "Fehlerhafte Eingabe im Feld " + identifier + ": Das Feld darf nicht leer sein."; break; 070 case 2: returnValue = "Fehlerhafte Eingabe im Feld " + identifier + ": Es werden Kommazahlen erwartet."; break; 071 case 3: returnValue = "Fehlerhafte Eingabe im Feld " + identifier + ": Es werden positive Zahlen erwartet."; break; 072 } 073 error = 0; 074 return returnValue; 075 } 076 }