KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > suberic > util > gui > propedit > NumberFilter


1 package net.suberic.util.gui.propedit;
2
3 /**
4  * A PropertyEditorListener which disallows non-integers, and can also be
5  * used for min/max settings.
6  */

7 public class NumberFilter extends PropertyEditorAdapter implements ConfigurablePropertyEditorListener {
8   String JavaDoc originalValue;
9
10   boolean checkMin = false;
11   int min;
12   boolean checkMax = false;
13   int max;
14
15   /**
16    * Configures this filter from the given key.
17    */

18   public void configureListener(String JavaDoc key, String JavaDoc property, String JavaDoc propertyBase, String JavaDoc editorTemplate, PropertyEditorManager manager) {
19     originalValue = manager.getProperty(property, "");
20
21     String JavaDoc minProp = manager.getProperty(key + ".min", "");
22     if (minProp != "") {
23       try {
24         min = Integer.parseInt(minProp);
25         checkMin = true;
26       } catch (NumberFormatException JavaDoc nfe) {
27       }
28     }
29
30     String JavaDoc maxProp = manager.getProperty(key + ".max", "");
31     if (maxProp != "") {
32       try {
33         max = Integer.parseInt(maxProp);
34         checkMax = true;
35       } catch (NumberFormatException JavaDoc nfe) {
36       }
37     }
38   }
39
40   /**
41    * Called when a property is about to change. If the value is not ok
42    * with the listener, a PropertyValueVetoException should be thrown.
43    *
44    * In this case, if the entry is either not a number, or is not within
45    * the min/max range, an error is thrown.
46    */

47   public void propertyChanging(PropertyEditorUI source, String JavaDoc property, String JavaDoc newValue) throws PropertyValueVetoException {
48     try {
49       if (newValue != null && newValue.length() > 0 && ! newValue.equals(originalValue)) {
50         int currentValue = Integer.parseInt(newValue);
51         if (checkMin) {
52           if (currentValue < min) {
53             throw new PropertyValueVetoException(property, newValue, "value must be at least " + min, this);
54           }
55         }
56
57         if (checkMax) {
58           if (currentValue > max) {
59             throw new PropertyValueVetoException(property, newValue, "value must be at most " + max, this);
60           }
61         }
62       }
63     } catch (NumberFormatException JavaDoc nfe) {
64       throw new PropertyValueVetoException(property, newValue, "entry must be a number.", this);
65     }
66   }
67
68 }
69
Popular Tags