1 |
|
|
2 |
|
|
3 |
|
|
4 |
|
|
5 |
|
package ca.spaz.gui; |
6 |
|
|
7 |
|
import java.awt.Toolkit; |
8 |
|
import java.text.DecimalFormat; |
9 |
|
|
10 |
|
import javax.swing.JTextField; |
11 |
|
import javax.swing.text.*; |
12 |
|
|
13 |
|
public class DoubleField extends JTextField { |
14 |
|
private Toolkit toolkit; |
15 |
|
private double min = Integer.MIN_VALUE, max = Integer.MAX_VALUE; |
16 |
|
private DecimalFormat df = new DecimalFormat("#########0.0###"); |
17 |
|
|
18 |
|
public DoubleField(double value, int columns) { |
19 |
|
super(columns); |
20 |
|
toolkit = Toolkit.getDefaultToolkit(); |
21 |
|
setValue(value); |
22 |
|
} |
23 |
|
|
24 |
|
public void setRange(double min, class="keyword">double max) { |
25 |
|
this.min = min; |
26 |
|
this.max = max; |
27 |
|
} |
28 |
|
|
29 |
|
public double getValue() { |
30 |
|
double retVal = 0; |
31 |
|
try { |
32 |
|
retVal = Double.parseDouble(getText()); |
33 |
|
} catch (NumberFormatException e) { |
34 |
|
toolkit.beep(); |
35 |
|
} |
36 |
|
if (retVal < min) retVal = min; |
37 |
|
if (retVal > max) retVal = max; |
38 |
|
return retVal; |
39 |
|
} |
40 |
|
|
41 |
|
public void setValue(double value) { |
42 |
|
if (value < min) value = min; |
43 |
|
if (value > max) value = max; |
44 |
|
setText(df.format(value)); |
45 |
|
|
46 |
|
} |
47 |
|
|
48 |
|
protected Document createDefaultModel() { |
49 |
|
return new DoubleDocument(); |
50 |
|
} |
51 |
|
|
52 |
|
protected String getCurrentText() { |
53 |
|
return getText(); |
54 |
|
} |
55 |
|
|
56 |
0 |
protected class DoubleDocument extends PlainDocument { |
57 |
|
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { |
58 |
0 |
char[] source = str.toCharArray(); |
59 |
0 |
char[] result = new class="keyword">char[source.length]; |
60 |
0 |
int j = 0; |
61 |
0 |
boolean decimal = false; |
62 |
0 |
for (int i = 0; i < result.length; i++) { |
63 |
0 |
char c = source[i]; |
64 |
0 |
if (Character.isDigit(c) || (c=='.' && getCurrentText().indexOf('.')==-1)) { |
65 |
0 |
result[j++] = c; |
66 |
0 |
if (c =='.') { |
67 |
0 |
decimal = true; |
68 |
0 |
} |
69 |
|
} else { |
70 |
0 |
toolkit.beep(); |
71 |
|
} |
72 |
|
} |
73 |
0 |
super.insertString(offs, new String(result, 0, j), a); |
74 |
0 |
} |
75 |
|
} |
76 |
|
} |