summaryrefslogtreecommitdiffstats
path: root/src/de/fhswf/in/inf/se/notepadMinusMinus/util/OverLimitIntegerStringConverter.java
blob: bec0ec0a4cf38712df19ee3131a269a8dab9e0f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package de.fhswf.in.inf.se.notepadMinusMinus.util;

import javafx.util.StringConverter;

/**
 * An {@link Integer} converter that checks the boundaries.
 *
 * @author Stefan Suhren
 * @version 1.0
 */
public class OverLimitIntegerStringConverter extends StringConverter<Integer>
{
   private int minAllowedValue;

   /**
    * Create and {@link OverLimitIntegerStringConverter} that uses the given
    * limit.
    *
    * @param minAllowedValue
    *           The smallest values that is still valid.
    */
   public OverLimitIntegerStringConverter(int minAllowedValue)
   {
      this.minAllowedValue = minAllowedValue;
   }

   /*
    * (non-Javadoc)
    * 
    * @see javafx.util.StringConverter#toString(java.lang.Object)
    */
   @Override
   public String toString(Integer object)
   {
      // If the specified value is null or not positive, return a zero-length
      // String
      if (object == null || object.intValue() < minAllowedValue)
      {
         return Integer.toString(minAllowedValue);
      }

      return (Integer.toString(object.intValue()));
   }

   /*
    * (non-Javadoc)
    * 
    * @see javafx.util.StringConverter#fromString(java.lang.String)
    */
   @Override
   public Integer fromString(String string)
   {
      // If the specified value is null or zero-length, return null
      if (string == null)
      {
         return null;
      }

      string = string.trim();

      if (string.length() < 1)
      {
         return minAllowedValue;
      }

      try
      {
         // If the specified value is 0 or negative, return null
         Integer object = Integer.valueOf(string);

         if (object.intValue() >= minAllowedValue)
         {
            return object;
         }
      }
      catch (NumberFormatException e)
      {
         // ignored
      }

      return minAllowedValue;
   }
}