1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.springframework.binding.value.swing;
17
18 import java.awt.event.FocusEvent;
19 import java.awt.event.FocusListener;
20 import java.util.ArrayList;
21 import java.util.Iterator;
22 import java.util.List;
23
24 import javax.swing.JFormattedTextField;
25 import javax.swing.text.BadLocationException;
26 import javax.swing.text.Document;
27
28
29
30
31
32
33 public class TestableJTextComponent extends JFormattedTextField {
34
35 private List focusListeners = new ArrayList();
36
37
38
39
40 public void gainFocus() {
41 FocusEvent focusEvent = new FocusEvent(this, FocusEvent.FOCUS_GAINED);
42 for (Iterator i = focusListeners.iterator(); i.hasNext();) {
43 ((FocusListener)i.next()).focusGained(focusEvent);
44 }
45 }
46
47
48
49
50 public void loseFocus() {
51 FocusEvent focusEvent = new FocusEvent(this, FocusEvent.FOCUS_LOST);
52 for (Iterator i = focusListeners.iterator(); i.hasNext();) {
53 ((FocusListener)i.next()).focusLost(focusEvent);
54 }
55 }
56
57
58
59
60 public void typeText(String text) {
61 Document doc = getDocument();
62 for (int i = 0; i < text.length(); i++) {
63 try {
64 doc.insertString(getCaretPosition(), new String(text.substring(i, i + 1)), null);
65 setCaretPosition(getCaretPosition() + 1);
66 }
67 catch (BadLocationException e) {
68 throw new UnsupportedOperationException(e.getMessage());
69 }
70 }
71 }
72
73
74
75
76 public void typeBackSpace() {
77 Document doc = getDocument();
78 try {
79 doc.remove(getCaretPosition() - 1, 1);
80 setCaretPosition(getCaretPosition() - 1);
81 }
82 catch (BadLocationException e) {
83 throw new UnsupportedOperationException(e.getMessage());
84 }
85 }
86
87 public void addFocusListener(FocusListener listener) {
88 super.addFocusListener(listener);
89 if (focusListeners != null) {
90 focusListeners.add(listener);
91 }
92 }
93 }