1 package com.bonevich.erj.ui.editor;
2
3 import javax.swing.JTextField;
4 import javax.swing.event.*;
5 import javax.swing.text.*;
6
7 public final class IdentifierTextField
8 extends JTextField implements DocumentListener
9 {
10
11 private Document _doc = new IdentifierDocument();
12
13 public IdentifierTextField()
14 {
15 setDocument(_doc);
16 }
17
18 /*** Prevent anyone from setting document */
19 public void setDocument(Document doc)
20 {
21 if (doc instanceof IdentifierDocument)
22 {
23 _doc = doc;
24 super.setDocument(doc);
25 }
26 }
27
28 //////////////////////////////////////////////////////////
29 // DocumentListener Implementation
30 public void changedUpdate(DocumentEvent e)
31 {
32 }
33
34 public void insertUpdate(DocumentEvent e)
35 {
36 String oldText = getText();
37 Document src = e.getDocument();
38 int offset = e.getOffset();
39 int length = e.getLength();
40 try
41 {
42 String newText = src.getText(offset, length);
43 _doc.insertString(offset, newText, null);
44 } catch (BadLocationException bpe) {
45 bpe.printStackTrace();
46 }
47 }
48
49 public void removeUpdate(DocumentEvent e)
50 {
51 String oldText = getText();
52 Document src = e.getDocument();
53 int offset = e.getOffset();
54 int length = e.getLength();
55 try
56 {
57 _doc.remove(offset, length);
58 } catch (BadLocationException bpe) {
59 bpe.printStackTrace();
60 }
61 }
62
63
64 /*** A <code>Document</code> implementation to control display and
65 * editing of an entity's identifier.
66 */
67 private static final class IdentifierDocument extends PlainDocument
68 {
69 //////////////////////////////////////////////////////////
70 // Constants
71 private static final String UNDERSCORE_STR = "_";
72
73 public void insertString(int offset, String s, AttributeSet set)
74 throws BadLocationException
75 {
76 for (int i = s.length() - 1; i >= 0; i--)
77 {
78 char ch = s.charAt(i);
79 String oneCh = String.valueOf(ch);
80 if (offset == 0 && i == 0)
81 {
82 if (!Character.isLetter(ch))
83 {
84 oneCh = UNDERSCORE_STR;
85 }
86 } else if (!Character.isLetterOrDigit(ch))
87 {
88 oneCh = UNDERSCORE_STR;
89 }
90 super.insertString(offset, oneCh, set);
91 }
92 }
93 } /*** end class IdentifierDocument */
94
95 }
This page was automatically generated by Maven