001 package market; 002 003 /** 004 * A ValueChecker, which checks if a String is in the format of an Integer (e.g. 1500).<br> 005 * 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 VCPositiveInteger 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 VCPositiveInteger(String identifier, boolean mayBeEmpty) { 033 this.identifier = identifier; 034 this.mayBeEmpty = mayBeEmpty; 035 } 036 037 /** 038 * @param identifier the identifier. 039 */ 040 public VCPositiveInteger(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 an Integer, otherwise <code>false</code>. 050 */ 051 public boolean isValidValue(String content) { 052 error = 0; 053 if (!mayBeEmpty && content.equals("")) { 054 error = 1; 055 } 056 if (!content.equals("") && error == 0) { 057 try { 058 if (!content.equals("")) { 059 Integer.parseInt(content); 060 } 061 } 062 catch (NumberFormatException e) { 063 error = 2; 064 } 065 } 066 if (!content.equals("") && error == 0) { 067 if (Integer.valueOf(content).intValue() < 0) error = 3; 068 } 069 return error == 0; 070 } 071 072 /** 073 * @return an error message depending on the value of {@link #error}. 074 */ 075 public String getErrorString() { 076 String returnValue = ""; 077 switch (error) { 078 case 1: 079 returnValue = "Fehlerhafte Eingabe im Feld " + identifier + ": Das Feld darf nicht leer sein."; 080 break; 081 case 2: 082 returnValue = "Fehlerhafte Eingabe im Feld " + identifier + ": Es sind nur ganzzahlige Werte erlaubt."; 083 break; 084 case 3: 085 returnValue = "Fehlerhafte Eingabe im Feld " + identifier + ": Es werden positive Zahlen erwartet."; 086 break; 087 } 088 error = 0; 089 return returnValue; 090 } 091 }