/
IntOnlyTextField.java
48 lines (38 loc) · 1.06 KB
/
IntOnlyTextField.java
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
import javax.swing.*;
import javax.swing.text.*;
/* This extension of JTextField only allows the entry of integers. */
class IntOnlyTextField extends JTextField {
public IntOnlyTextField(String str, int cols) {
super(str, cols);
}
protected Document createDefaultModel() {
return new IntOnlyDocument();
}
static class IntOnlyDocument extends PlainDocument {
public void insertString(int offset, String str, AttributeSet a)
throws BadLocationException {
/* Don't do anything if there is nothing to insert! */
if (str == null) {
return;
}
/* Insert the string if it is formatted properly. */
try {
int i = Integer.parseInt(str);
} catch (NumberFormatException e) {
/* Don't do anything if the string is misformatted. */
return;
}
super.insertString(offset, str, a);
}
}
/* Return whatever is in the field as an integer value. */
public int getValue() {
int i;
try {
i = Integer.parseInt(getText());
} catch (NumberFormatException e) {
return 0;
}
return i;
}
}