1 19 package org.netbeans.modules.xml.tools.generator; 20 21 import java.awt.*; 22 import java.awt.event.*; 23 24 import javax.swing.*; 25 import javax.swing.text.*; 26 import javax.swing.event.*; 27 28 38 public class ValidatingTextField extends JTextField implements ComboBoxEditor { 39 40 private static final long serialVersionUID = 23746913L; 41 42 private transient Validator validator = null; 43 44 private transient String tooltip = null; 46 private transient DocumentListener adapter = null; 47 48 public ValidatingTextField() { 49 50 KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); 52 Keymap map = getKeymap(); 53 map.removeKeyStrokeBinding(enter); 54 55 } 56 57 61 public void setValidator(Validator validator) { 62 63 Validator old = this.validator; 64 65 this.validator = validator; 66 67 if (old == null && validator != null) { 68 69 71 adapter = new DocumentListener() { 72 public void insertUpdate(DocumentEvent e) { feedback(); } 73 public void removeUpdate(DocumentEvent e) { feedback(); } 74 public void changedUpdate(DocumentEvent e) {} 75 }; 76 77 getDocument().addDocumentListener(adapter); 78 79 } else if (old != null && validator == null) { 80 81 83 getDocument().removeDocumentListener(adapter); 84 85 adapter = null; 86 } 87 88 feedback(); 89 90 } 91 92 private void feedback() { 96 97 99 SwingUtilities.invokeLater( new Runnable () { 100 public void run() { 101 if (validator == null || validator.isValid(getText())) { 102 ValidatingTextField.super.setToolTipText(tooltip); 103 ValidatingTextField.this.setForeground(Color.black); 104 } else { 105 String reason = validator.getReason(); 106 ValidatingTextField.super.setToolTipText(reason == null ? Util.THIS.getString("MSG_invalid") : reason); 107 ValidatingTextField.this.setForeground(Color.red); 108 } 109 } 110 }); 111 } 112 113 115 public java.lang.Object getItem() { 116 return getText(); 117 } 118 119 public void setItem(java.lang.Object obj) { 120 setText((String ) obj); 121 } 122 123 public java.awt.Component getEditorComponent() { 124 return this; 125 } 126 127 130 public void setToolTipText(String text) { 131 tooltip = text; 132 feedback(); 133 } 134 135 139 public static interface Validator { 140 141 144 public boolean isValid(String text); 145 146 149 public String getReason(); 150 } 151 152 } 153 | Popular Tags |