1 package org.wcb.gui.component;
2
3 import javax.swing.*;
4 import javax.swing.text.Document;
5 import javax.swing.text.PlainDocument;
6 import javax.swing.text.BadLocationException;
7 import javax.swing.text.AttributeSet;
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 public class IntegerJTextField extends JTextField {
35 private long maxValue = Long.MAX_VALUE;
36 private long minValue = 0;
37 private int maxLength = String.valueOf(maxValue).length();
38 private boolean isIPField = false;
39
40
41
42
43 public IntegerJTextField()
44 {
45 super();
46 }
47
48
49
50
51 public IntegerJTextField(int column)
52 {
53 super(column);
54 }
55
56 protected Document createDefaultModel()
57 {
58 return new IntegerDocument();
59 }
60
61 public void setMinValue(long value)
62 {
63 minValue = value;
64 }
65
66 public long getMinValue()
67 {
68 return minValue;
69 }
70
71
72 public void setIPField(boolean value)
73 {
74 isIPField = value;
75 }
76
77 public boolean getIPField()
78 {
79 return isIPField;
80 }
81
82 public void setMaxValue(long value)
83 {
84 maxValue = value;
85 }
86
87 public long getMaxValue()
88 {
89 return maxValue;
90 }
91
92 public void setMaxLength(int value)
93 {
94 maxLength = value;
95 }
96
97 public int getMaxLength()
98 {
99 return maxLength;
100 }
101
102
103 private class IntegerDocument extends PlainDocument {
104 public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
105 long typedValue;
106
107 StringBuffer textBuffer = new StringBuffer(IntegerJTextField.this.getText().trim());
108
109 if((offs >= 0) && (offs <= textBuffer.length()))
110 {
111 textBuffer.insert(offs,str);
112 String textValue = textBuffer.toString();
113 if(textBuffer.length() > maxLength)
114 {
115 JOptionPane.showMessageDialog(IntegerJTextField.this, "The number of characters must be less than or equal to " + getMaxLength(), "Error Message",JOptionPane.ERROR_MESSAGE);
116 return;
117 }
118
119 if((textValue == null) || (textValue.equals("")))
120 {
121 remove(0,getLength());
122 super.insertString(0, "", null);
123 return;
124 }
125
126 if(textValue.equals("-") && minValue < 0)
127 {
128 super.insertString(offs, str, a);
129 return;
130 }
131
132
133 if(str.equals(".") && isIPField)
134 {
135 super.insertString(offs, str,a);
136 return;
137 }
138 else
139 {
140 try
141 {
142 typedValue = Long.parseLong(textValue);
143 if((typedValue > maxValue) || (typedValue < minValue))
144 {
145 JOptionPane.showMessageDialog(IntegerJTextField.this, "The value can only be from "+getMinValue()+" to " + getMaxValue(), "Error Message", JOptionPane.ERROR_MESSAGE);
146 }
147 else
148 {
149 super.insertString(offs, str,a);
150 }
151 }
152 catch(NumberFormatException ex)
153 {
154 JOptionPane.showMessageDialog(IntegerJTextField.this, "Only numeric values allowed.", "Error Message", JOptionPane.ERROR_MESSAGE);
155 }
156 }
157 }
158 }
159 }
160 }